如何使用PHP Simple DOM DOM解析器添加自定义属性 [英] how to add a custom attributes with PHP Simple HTML DOM Parser

查看:607
本文介绍了如何使用PHP Simple DOM DOM解析器添加自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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";
}

但这不起作用。

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

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.

推荐答案

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

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

输出:

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

这篇关于如何使用PHP Simple DOM DOM解析器添加自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆