我想使用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值。谢谢!