2

I have a file test.xml

<?xml version="1.0" encoding="UTF-8"?>
<item>
<dc:creator><![CDATA[hello world]]></dc:creator>
</item>

and code php

$doc = new DOMDocument();
$doc->load('test.xml');
$items = $doc->getElementsByTagName('item');
foreach ($items as $item) {
   $authors = $item->getElementsByTagName( "dc:creator" );
   $author = $authors->item(0)->nodeValue;
   echo $author;
}

=> error can't get value, how to get this, result is "hello world"

1
  • 1
    "dc" here is a namespace, which does not get considered as part of the "tag name". Try getElementsByTagNameNS. Commented Apr 9, 2013 at 5:10

1 Answer 1

3

You are using the wrong element name. The method getElementsByTagName expects the local-name, that is creator in your case.

You can see that if you load your sample XML

<?xml version="1.0" encoding="UTF-8"?>
<item>
<dc:creator><![CDATA[hello world]]></dc:creator>
</item>

into the DOMDocument. You get a warning:

Warning: DOMDocument::loadXML(): Namespace prefix dc on creator is not defined in Entity

Because the namespace prefix is not defined, DOMDocument will remove it. This results in the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<item xmlns:dc="ns:1">
<creator><![CDATA[hello world 2]]></creator>
</item>

As you can see there is no element with the local name creator with an xmlns-prefix dc (<dc:creator>)any longer.

But as you're like have pasted the wrong XML for your example and likely the namespace prefix is defined in your real XML, you're just asking how to access tags with a namespace prefix (that is the part before the colon :). This has already been outlined here:

If you want an element which's tag is inside a namespace of its own, you need to tell DOMDocument which namespace you mean:

$dcUri   = $doc->lookupNamespaceUri('dc');
$authors = $item->getElementsByTagNameNS($dcUri, 'creator');
$author  = $authors->item(0)->nodeValue;
Sign up to request clarification or add additional context in comments.

Comments

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.