doushuo8677 2015-12-10 10:49
浏览 209
已采纳

如何使用PHP xpath获取所有属性?

Given the following HTML string:

<div 
class="example-class" 
data-caption="Example caption" 
data-link="https://www.example.com" 
data-image-url="https://example.com/example.jpg">
</div>

How can I use PHP with xpath to output / retrieve an array with all attributes as key / value pairs?

Hoping for output like:

Array
(
    [data-caption] => Example caption
    [data-link] => https://www.example.com
    [data-image-url] => https://example.com/example.jpg
)
// etc etc...

I know how to get individual attributes, but I'm hoping to do it in one fell swoop. Here's what I currently have:

function get_data($html = '') {

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom);

    $nodes = $xpath->query('//div/@data-link');

    foreach ($nodes as $node) {
        var_dump($node);
    }

}

Thanks!

  • 写回答

2条回答

  • dongshan7060 2015-12-10 11:43
    关注

    In XPath, you can use @* to reference attributes of any name, for example :

    $nodes = $xpath->query('//div/@*');
    
    foreach ($nodes as $node) {
        echo $node->nodeName ." :  ". $node->nodeValue ."<br>";
    }
    

    <kbd>eval.in demo</kbd>

    output :

    class :  example-class
    data-caption :  Example caption
    data-link :  https://www.example.com
    data-image-url :  https://example.com/example.jpg
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大