I'm parsing xml document using DOMDocument class. First I've selected all nodes with name 'item' using $xml->getElementsByTagName('item')
method. My sample xml file looks like this:
<item>
<title>...</link>
<description>...</description>
<pubDate>...</pubDate>
<ns:author>...</dc:creator>
</item>
However my problem is getting value from nested tag with namespace name with colon sign. I get values from nodes without namespaces in foreach
using $node->getElementsByTagName('description')->item(0)->nodeValue
and there is no errors.
I also found method getElementsByTagNameNs() to get nodes with it's namespaces. However when i try to get nodeValue like previous nodes without namespace I get "PHP Notice: Trying to get property of non-object". I think it is strange because getElementsByTagNameNs()->item(0)
returns object DOMElement.
Do you know how to take value from node with namespace, in this case <ns:author></dc:creator>
element?
As the document fragment you give isn't complete and even valid, I've had to make a few changes. You say you want the value of <ns:author>...</dc:creator>
which is not a valid element as the open and close names are different in both name and namespace, you would expect something like <ns:author>...</ns:author>
As an example of how you can fetch the values from a namespace (using some corrected and some guessed alterations to the XML)...
$xml = <<<XML
<?xml version="1.0"?>
<items xmlns:ns="http://some.url">
<item>
<title>title</title>
<description>Descr.</description>
<pubDate>1/1/1970</pubDate>
<ns:author>author1</ns:author>
</item>
</items>
XML;
$dom = new DOMDocument( '1.0', 'utf-8' );
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('item');
foreach ( $items as $item ) {
$author = $item->getElementsByTagNameNS("http://some.url", "*")->item(0)->nodeValue;
echo "Author = ".$author.PHP_EOL;
}
In getElementsByTagNameNS()
you will need to put in the correct URL for this namespace, which should be in the source document.
This outputs...
Author = author1