0

I'm having two problems. Getting XPATH to work with atom namespace and getting data from a CDATA field.

The xml that I have looks like

<?xml version="1.0" encoding="UTF-8" ?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:kml="http://www.opengis.net/kml/2.2">
    <title type="text"><![CDATA[Hello World]]></title>
</entry>

While my PHP looks like

 $xml = new SimpleXMLElement(file_get_contents($this->xmlFile));
 $xml->setAttributeNS( "http://www.w3.org/2005/Atom");
 $xml->registerXpathNamespace('kml' , 'http://www.opengis.net/kml/2.2');

 $result = $xml->xpath('/entry/title');
 var_dump($result);

Removing the atom namespace from the XML allows my xpath to work. But how do I get simplexml to accept atom as a namespace? Also when I do get data (without atom) I can't get the text because it's formatted as CDATA, how can I get show the CDATA text?

user2988129
  • 191
  • 3
  • 13
  • kml isn't the only namespace being used, and entry doesn't have a namespace. – user2988129 Nov 21 '13 at 15:53
  • @MarcB & @user2988129 the namespace `kml` is even not used in the input XML. All elements in the shown input XML are all belonging to the default namespace (without the prefix). – Mark Veenstra Nov 21 '13 at 15:56
  • Stackoverflow works best by asking one question at a time, for example: [SimpleXmlElement and XPath, getting empty array()](http://stackoverflow.com/q/4024197/367456); [PHP: How to handle <![CDATA[ with SimpleXMLElement?](http://stackoverflow.com/q/2970602/367456) – hakre Nov 23 '13 at 14:39

1 Answers1

2

From the PHP documentation (http://us1.php.net/manual/en/domelement.setattributens.php):

Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.

You do not want to set a namespace, but you want to declare it so you can use it, so change:

$xml->setAttributeNS( "http://www.w3.org/2005/Atom");

To:

$xml->registerXpathNamespace('atom' , 'http://www.w3.org/2005/Atom');

After that you can use that prefix into your XPath:

$result = $xml->xpath('/atom:entry/atom:title');
Mark Veenstra
  • 4,691
  • 6
  • 35
  • 66