0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

What if the namespace isn't specified in the file and you just want to use a specific string as the namespace?
@Aaron, normally the namespace would have to be defined for it to be valid XML. If this is not the case, I would suggest asking a question with the XML and what you have so far.
Thanks for your reply. I used SimpleXML and ->attributes('namespace', true) instead and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.