Gloytos htyqo
Gloytos htyqo

Reputation: 355

How to find first img within the XML using SimpleXML?

I have this XML code

<entry>
<p>11</p>
<p>22</p>
<p>33<img src="1.jpg"/></p>
<p>44</p>
</entry>

and I want to select the first image and get the src of it

The problem is because the img is not always at third child so its inside <entry> but I don't know exactly where it is, so I need to search first image and not to find like this.

 p[2]->img[src]

 $children->entry->img[src];

Upvotes: 0

Views: 367

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

You can use XPath to find the <img> tag and extract the src attribute using //img/@src which finds any img element with a src attribute (using @ to indicate it is an attribute)...

$data = '<entry>
<p>11</p>
<p>22</p>
<p>33<img src="1.jpg"></img></p>
<p>44</p>
</entry>';

$xml = simplexml_load_string($data);
$image = $xml->xpath("//img/@src");
echo (string)$image[0];

will echo

1.jpg

As xpath() will return a list of matches, you need to use [0] to limit it to the first match and casting to a string ((string)) ensures you have a string as opposed to any form of SimpleXMLElement.

Update:

With the extra XML content in the real sample, there are a few more stages to get the images. A default namespace needs to be defined to allow you to fetch the content element - which contains the data you are after. Then there are a few bits of manipulation of this data (remove some HTML which causes XML problems also as it's a document fragment, add in a new root element) and load this into a second level XML. Then you can extract the src attributes.

$xml = simplexml_load_file("city.xml");
$xml->registerXPathNamespace("d", "http://www.w3.org/2005/Atom");
$content = $xml->xpath("//d:content");
foreach ( $content as $cont )   {
    $newXML = "<root>".(string)$cont."</root>";
    $newXML = str_replace(["&nbsp;", "allowfullscreen"], " ", $newXML);
    $xml2 = simplexml_load_string($newXML);
    $image = $xml2->xpath("//img/@src");
    foreach ( $image as $imgSrc ){ 
        echo (string)$imgSrc.PHP_EOL;
    }
}

Upvotes: 1

Related Questions