2
<url> <loc> <![CDATA[ https://www.news18.com/photogallery/photogallery/in-photos-five-most-expensive-face-masks-for-protection-from-covid-19-in-the-world-3519821.html ]]> </loc> <image:image> <image:loc> <![CDATA[ https://images.news18.com/ibnlive/uploads/2021/03/1615377235_mask-1.jpg ]]> </image:loc> <image:caption> <![CDATA[ ]]> </image:caption> </image:image> <image:image> <image:loc> <![CDATA[ https://images.news18.com/ibnlive/uploads/2021/03/1615377250_mask-2.jpg ]]> </image:loc> <image:caption> <![CDATA[ ]]> </image:caption> </image:image> </url> 

How can I Select image:image element in php if i write $xml->url->image:image | It Will be Wrong Syntax

3

1 Answer 1

5

It is a good idea to familiarize yourself with XML Namespaces first.

I'm going to assume that at a higher level you have something that is explaining what image: represents. If you don't, that's a different problem and you arguably don't have XML, just something that looks a lot like it. Here's you exact same XML but wrapped in what I assume is an Image Sitemap as defined by Google.

$xml = <<<'TAG' <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"> <url> <loc> <![CDATA[ https://www.news18.com/photogallery/photogallery/in-photos-five-most-expensive-face-masks-for-protection-from-covid-19-in-the-world-3519821.html ]]> </loc> <image:image> <image:loc> <![CDATA[ https://images.news18.com/ibnlive/uploads/2021/03/1615377235_mask-1.jpg ]]> </image:loc> <image:caption> <![CDATA[ ]]> </image:caption> </image:image> <image:image> <image:loc> <![CDATA[ https://images.news18.com/ibnlive/uploads/2021/03/1615377250_mask-2.jpg ]]> </image:loc> <image:caption> <![CDATA[ ]]> </image:caption> </image:image> </url> </urlset> TAG; 

To access things by a namespace, you call children() on the node with the appropriate namespace expansion:

$doc = simplexml_load_string($xml); echo $doc->url[0]->children('http://www.google.com/schemas/sitemap-image/1.1')->image->loc; 

This prints out:

 https://images.news18.com/ibnlive/uploads/2021/03/1615377235_mask-1.jpg 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, This Worked Well!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.