在PHP中使用simplehtmldom如何获取data-href属性


Using simplehtmldom in PHP how do I get the data-href attribute?

我正在使用这个PHP库来处理dom :http://simplehtmldom.sourceforge.net/

我想访问此页面上li元素的data-href元素:http://www.spareroom.co.uk/flatshare/bristol/

根据 API 参考:http://simplehtmldom.sourceforge.net/manual_api.htm

这段代码应该可以工作 - 只要$res代表 li dom 节点 - 在我的情况下它确实如此:

echo $res->data-href;

但是当我运行时,回声是"0"....当我希望看到类似的东西时:

"/flatshare/fad_click.pl?fad_id=3248085&search_id=&offset=0&city_id=&flatshare_type=offered&search_results=%2Fflatshare%2Fbristol%2F&"

有人可以帮我了解我做错了什么吗

$res->data-href解析为

$res->data - href

即它是一个减法,因为-不是标识符中的有效字符。尝试:

$res->{"data-href"}

由于您正在访问对象,因此必须用特殊字符将键括起来并用 {} 括起来。所以:

echo $res->data-herf

应该是:

echo $res->{"data-href"}

老实说,尽管使用该方法可能更容易(也更安全):

$res->getAttribute("data-href");