我正在一个需要使用PHP Simple HTML Dom Parser的项目中工作,并且我需要一种基于类名将自定义属性添加到许多元素的方法。
我可以使用foreach循环遍历元素,并且设置标准属性(例如href)很容易,但是我找不到添加自定义属性的方法。
我能猜到的最接近的是:
foreach($html -> find(".myelems") as $element) {
$element->myattr="customvalue";
}
但这是行不通的。
我在类似主题上还看到了许多其他问题,但是它们都建议使用一种替代方法来解析html(domDocument等)。就我而言,这不是一个选择,因为我必须使用简单HTML DOM解析器。
你试过了吗?请尝试以下示例(示例:添加数据标签)。
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句