How can I get img src using php domxpath

Home / Uncategorized / How can I get img src using php domxpath

Question:
I want to get the img src value using domxpath.

Let us say I have this sample.html page:

Sample 1

Sample 2

Sample 3

Using CURL, DOMDocument and DOMXPath I want to get the img src and the title:$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;
This will result to img as null:[
{
"img": null,
"title": "Sample 1"
},
{
"img": null,
"title": "Sample 2"
},
{
"img": null,
"title": "Sample 3"
}
]
Please help me on how to get the img src value. Thank You!


Answer:
Your XPath in fetching the values isn’t quite correct, should be…
$result[‘img’] = $xpath->query("//img/@src", $entry)[0]->value;
$result[‘title’] = $xpath->query("//p[@class=’title’]", $entry)[0]->nodeValue;
Note the way you get the attributes is by using @attibuteName. Also the // at the start allows XPath to find the elements at any point under the start point.
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *