如何使用PHP Simple HTML DOM Parser添加自定义属性

时间:2014-07-04 13:28:48

标签: php html html5 simple-html-dom

我正在使用一个需要使用PHP Simple HTML Dom Parser的项目,我需要一种方法来根据类名向一些元素添加自定义属性。

我可以使用foreach循环遍历元素,并且可以很容易地设置标准属性,例如href,但我找不到添加自定义属性的方法。

我猜的最接近的是:

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

但这不起作用。

我在类似主题上看到了许多其他问题,但他们都建议使用另一种方法来解析html(domDocument等)。在我的情况下,这不是一个选项,因为我必须使用简单的HTML DOM解析器。

2 个答案:

答案 0 :(得分:5)

你尝试过吗?试试这个例子(示例:添加数据标签)。

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);

输出:

<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>

答案 1 :(得分:0)

好吧,我认为这是一个过时的帖子,但我仍然认为它将对像我这样的人有所帮助:)

因此,在我的情况下,我向图像标签添加了自定义属性

$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');
}