【问题标题】:How can I get img src using php domxpath如何使用 php domxpath 获取 img src
【发布时间】:2017-08-12 06:46:02
【问题描述】:

我想使用 domxpath 获取 img src 值。

假设我有这个 sample.html 页面:

<div id="wrapper">
    <div class="item">
        <div class="img-wrapper">
            <img src="sample1.jpg"/>
            <p class="title">Sample 1</p>
        </div>
    </div>
    <div class="item">
        <div class="img-wrapper">
            <img src="sample2.jpg"/>
            <p class="title">Sample 2</p>
        </div>
    </div>
    <div class="item">
        <div class="img-wrapper">
            <img src="sample3.jpg"/>
            <p class="title">Sample 3</p>
        </div>
    </div>
</div>

使用 CURL、DOMDocument 和 DOMXPath 我想获取 img src 和标题:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://path/to/sample.html');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
curl_close($ch);

$dom = new DOMDocument();
$dom->loadHTML($result);
$xpath = new DOMXPath($dom);
$entries = $xpath->query('//div[@id="wrapper"]/div[@class="item"]');
$results = array();
foreach ($entries as $entry) {
    $result = array();
    $result['img'] = $xpath->query("img", $entry)->item(0)->nodeValue;
    $result['title'] = $xpath->query("p[@class='title']", $entry)->item(0)->nodeValue;
    $results[] = $result;
}
return $results;

这将导致 img 为 null:

[
    {
        "img": null,
        "title": "Sample 1"
    },
    {
        "img": null,
        "title": "Sample 2"
    },
    {
        "img": null,
        "title": "Sample 3"
    }
]

请帮助我了解如何获取 img src 值。谢谢!

【问题讨论】:

    标签: php html curl domdocument domxpath


    【解决方案1】:

    您在获取值时的 XPath 不太正确,应该是...

    $result['img'] = $xpath->query("//img/@src", $entry)[0]->value;
    $result['title'] = $xpath->query("//p[@class='title']", $entry)[0]->nodeValue;
    

    注意获取属性的方式是使用@attibuteName。此外,开头的 // 允许 XPath 在起点下的任何点找到元素。

    【讨论】:

      【解决方案2】:

      你可以使用getAttribute('attribute_name')方法获取任意DOM元素的属性

      在您的示例中使用getAttribute('src')

      $result['img'] = $xpath->query("//img", $entry)->item(0)->getAttribute('src');
      $result['title'] = $xpath->query("//p[@class='title']", $entry)->item(0)->nodeValue;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 2017-11-16
        • 1970-01-01
        • 1970-01-01
        • 2013-04-09
        • 2014-07-08
        • 2023-03-19
        相关资源
        最近更新 更多