【问题标题】:php xpath how to get values from multiple elements inside a parent elementphp xpath如何从父元素内的多个元素中获取值
【发布时间】:2021-06-19 14:35:22
【问题描述】:

我需要从特定站点收集所有这些数据。我需要 URL、图像、文本。这是我尝试使用的代码。但我需要从页面上的所有标签中收集所有信息。

<article>
    <a href="http://www.link.com">
      <div><img src="https://image.com/image.png" /></div>
      <div>History</div>
      <div><h3>Content Here.</h3></div>
</article>
<article>
    <a href="http://www.link.com">
      <div><img src="https://image.com/image.png" /></div>
      <div>History</div>
      <div><h3>Content Here.</h3></div>
</article>
<article>
    <a href="http://www.link.com">
      <div><img src="https://image.com/image.png" /></div>
      <div>History</div>
      <div><h3>Content Here.</h3></div>
</article>

php代码

$html = file_get_contents($feed_url);
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new DomXPath($dom);
        $articles = $xpath->query("//article");
        $items = array();

        foreach($articles as $article) {
                $link = $xpath->query("//a/@href", $article);
                $img = $xpath->query("//img/@src", $article);
                $link = $xpath->query("//h3", $article);
        }

我似乎无法让它返回任何值。我可以通过 foreach 得到一个值。但我也需要所有其他人。我无法完全弄清楚如何做到这一点。任何帮助将不胜感激。

【问题讨论】:

    标签: php dom xpath


    【解决方案1】:

    如果我像这样更改您的 foreach 循环:

    foreach($articles as $article) {
            $link = $xpath->query(".//a/@href", $article);
            $img = $xpath->query(".//img/@src", $article);
            $head = $xpath->query(".//h3", $article);
            echo $link[0]->nodeValue . "  ". $img[0]->nodeValue  . "  ". $head[0]->nodeValue . "\n";
    }
    

    我将其作为输出(我在元素中添加了数字只是为了区分树 &lt;article&gt; 节点:

    http://www.link1.com  https://image.com/image1.png  Content1 Here.
    http://www.link2.com  https://image.com/image2.png  Content2 Here.
    http://www.link3.com  https://image.com/image3.png  Content3 Here.
    

    这就是你要找的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2013-08-10
      • 1970-01-01
      • 2019-02-19
      • 2011-07-10
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多