how to add a custom attributes with PHP Simple HTM

2019-02-26 05:45发布

问题:

I am working with a project that require the use of PHP Simple HTML Dom Parser, and I need a way to add a custom attribute to a number of elements based on class name.

I am able to loop through the elements with a foreach loop, and it would be easy to set a standard attribute such as href, but I can't find a way to add a custom attribute.

The closest I can guess is something like:

foreach($html -> find(".myelems") as $element) {
     $element->myattr="customvalue";
}

but this doesn't work.

I have seen a number of other questions on similar topics, but they all suggest using an alternative method for parsing html (domDocument etc.). In my case this is not an option, as I must use Simple HTML DOM Parser.

回答1:

Did you try it? Try this example (Sample: adding data tags).

include 'simple_html_dom.php';

$html_string = '
<style>.myelems{color:green}</style>
<div>
    <p class="myelems">text inside 1</p>
    <p class="myelems">text inside 2</p>
    <p class="myelems">text inside 3</p>
    <p>simple text 1</p>
    <p>simple text 2</p>
</div>
';

$html = str_get_html($html_string);
foreach($html->find('div p[class="myelems"]') as $key => $p_tags) {
    $p_tags->{'data-index'} = $key;
}

echo htmlentities($html);

Output:

<style>.myelems{color:green}</style> 
<div> 
    <p class="myelems" data-index="0">text inside 1</p> 
    <p class="myelems" data-index="1">text inside 2</p> 
    <p class="myelems" data-index="2">text inside 3</p> 
    <p>simple text 1</p> 
    <p>simple text 2</p> 
</div>