I'm new to PHP and I would like to know how to retrieve data from an HTML element such as an src
?
It's very easy to do that in jQuery:
$('img').attr('src');
But I have no idea how to do it in PHP (if it is possible).
Here's an example I'm working on:
I loaded $result
into SimpleXMLElement and stored it into $xml
:
$xml = simplexml_load_string($result) or die("Error: Cannot create object");
Then used foreach
to loop over all elements:
foreach($xml->links->link as $link){ echo 'Image: ' . $link->{'link-code-html'}[0] . '</br>'; // returns sometihing similar to: <a href='....'><img src='....'></a> }
Inside of the foreach
I'm trying to access links ( src
) in img
.
Is there a way to access src
of the img
nested inside of the a
— clear when outputted to the screen:
echo 'Image: ' . $link->{'link-code-html'}[0] . '</br>';
I would do this with the built-in DOMDocument
and DOMXPath
APIs, and then you can use the getAttribute
method on any matching img
node:
$doc = new DOMDocument();
// Load some example HTML. If you need to load from file, use ->loadHTMLFile
$doc->loadHTML("<a href='abc.com'><img src='ping1.png'></a>
<a href='def.com'><img src='ping2.png'></a>
<a href='ghi.com'>something else</a>");
$xpath = new DOMXpath($doc);
// Collect the images that are children of anchor elements
$imgs = $xpath->query("//a/img");
foreach($imgs as $img) {
echo "Image: " . $img->getAttribute("src") . "\n";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.