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

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)