SimpleXML: working with XML containing namespaces

I am trying to get to geoinformation with google-picasa API. This is the original XML:

<georss:where> <gml:Point> <gml:pos>35.669998 139.770004</gml:pos> </gml:Point> </georss:where> 

I have already gone so far with:

 $ns_geo=$item->children($namespace['georss']); $geo=$ns_geo->children($namespace['gml']); 

var_dump($geo) prints

 object(SimpleXMLElement)#34 (1) { ["Point"]=> object(SimpleXMLElement)#30 (1) { ["pos"]=> string(18) "52.373801 4.890935" } } 

but

 echo (string)$geo->position or (string)$geo->position->pos; 

will give nothing. Is there something obvious I'm doing wrong?

+1
source share
3 answers

You can work with XPath and registerXPathNamespace() :

 $xml->registerXPathNamespace("georss", "http://www.georss.org/georss"); $xml->registerXPathNamespace("gml", "http://www.opengis.net/gml"); $pos = $xml->xpath("/georss:where/gml:Point/gml:pos"); 

From the documents, my emphasis is:

registerXPathNamespace [...] Creates a prefix / ns context for the next XPath request .

Additional ways to handle namespaces in SimpleXML can be found here, for example:
Stuart Herbert In PHP - Using SimpleXML To Analyze RSS Feeds

+4
source
 echo $geo->pos[0]; 
0
source

Here is how I did it without using xpath:

 $georss = $photo->children('http://www.georss.org/georss'); $coords; if($georss->count()>0) { $gml = $georss->children('http://www.opengis.net/gml'); if($gml->count()>0) { if(isset($gml->Point->pos)) { $coords = $gml->Point->pos; } } } 
0
source

Source: https://habr.com/ru/post/1337174/


All Articles