how to add a custom attributes with PHP Simple HTML DOM Parser

喜夏-厌秋 提交于 2019-12-02 05:36:28

问题


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>



回答2:


Well, I think it's too old post but still i think it will help somebody like me :)

So in my case I added custom attribute to an image tag

$markup = file_get_contents('pathtohtmlfile');

//Create a new DOM document
$dom = new DOMDocument;

//Parse the HTML. The @ is used to suppress any parsing errors
//that will be thrown if the $html string isn't valid XHTML.
@$dom->loadHTML($markup);

//Get all images tags
$imgs = $dom->getElementsByTagName('img');

//Iterate over the extracted images
foreach ($imgs as $img)
{
    $img->setAttribute('customAttr', 'customAttrVal');
}


来源:https://stackoverflow.com/questions/24575475/how-to-add-a-custom-attributes-with-php-simple-html-dom-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!