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"

hakre
  • 193,403
  • 52
  • 435
  • 836
Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102
  • 1
    "dc" here is a namespace, which does not get considered as part of the "tag name". Try [`getElementsByTagNameNS`](http://www.php.net/manual/en/domelement.getelementsbytagnamens.php). – Passerby Apr 09 '13 at 05:10

1 Answers1

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;
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836