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

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

图片转代码服务由CSDN问答提供 功能建议

给定以下HTML字符串:

 &lt; div \  nclass =“example-class”
data-caption =“示例标题”
data-link =“https://www.example.com”
data-image-url =“https://example.com/example。  jpg“&gt; 
&lt; / div&gt; 
   
 
 

如何使用带xpath的PHP输出/检索具有键/值对所有属性的数组?< / p>

希望输出如:

  Array 
(
 [data-caption] =&gt;示例标题
 [数据 -  链接] =&gt; https://www.example.com 
 [data-image-url] =&gt; https://example.com/example.jpg
)
//等等... \  n   
 
 

我知道如何获得个人属性,但我希望能一下子做到。 这是我目前所拥有的:

  function get_data($ html =''){
 
 $ dom = new DOMDocument(); 
 $ dom-&gt; loadHTML  ($ html); 
 $ xpath = new DOMXPath($ dom); 
 
 $ nodes = $ xpath-&gt; query('// div / @ data-link'); 
 
 foreach($ 节点为$ node){
 var_dump($ node); 
} 
 
} 
   
 
 

谢谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    eval.in demo

    output :

    class :  example-class
    data-caption :  Example caption
    data-link :  https://www.example.com
    data-image-url :  https://example.com/example.jpg
    
    打赏 评论
  • dongshenjie3055 2015-12-10 11:09

    I think this should do what you want - or at least, give you the basis to proceed.

        define('BR','<br />');
        $strhtml='<div 
            class="example-class" 
            data-caption="Example caption" 
            data-link="https://www.example.com" 
            data-image-url="https://example.com/example.jpg">
            </div>';
    
        $dom=new DOMDocument;
        $dom->loadHTML( $strhtml );
    
        $xpath=new DOMXPath( $dom );
        $col=$xpath->query('//div');
        if( $col ){
            foreach( $col as $node ) if( $node->nodeType==XML_ELEMENT_NODE ) {
                foreach( $node->attributes as $attr ) echo $attr->nodeName.' '.$attr->nodeValue.BR;
            }
        }
        $dom = $col = $xpath = null;
    
    打赏 评论

相关推荐 更多相似问题