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

如何使用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条)

报告相同问题?