8bitmagic 8bitmagic - 1 year ago 57
PHP Question

XML namespaces - how to get them?

Been trying to extract some XML with namespaces in it. I've tried to understand this myself; but I can't seem to identify exactly whats wrong with what I'm doing.

I have this set to variable

, and running the following code to spit out the title attribute:

<getmatchingproductresponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<getmatchingproductresult asin="055726328X" status="Success">
<ns2:itemattributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
<ns2:title>You Are a Spiritual Healer</ns2:title>


$sxe=new SimpleXMLElement($myXMLData);
foreach ($result as $title)
echo $title . "<br>";

But my output is blank. What am I doing wrong here? Please help...!

Answer Source

You did register the wrong namespace in the nopaste. Here are two namespaces in the document.

  • http://mws.amazonservices.com/schema/Products/2011-10-01
    elements without a prefix
  • http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd
    element with prefix ns2

The title uses the prefix ns2. You don't have to register the prefixes used in the document. You can and should just register you own. In SimpleXML you will have to do that on any element you like to call the method xpath() on. It helps creating a small function for it.

$xmlns = [
  'p' => 'http://mws.amazonservices.com/schema/Products/2011-10-01',
  'pd' => 'http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd'

function registerNamespacesOnElement(
  SimpleXMLElement $element, array $namespaces
) {
  foreach ($namespaces as $prefix => $namespace) {
    $element->registerXpathNamespace($prefix, $namespace);

$sxe=new SimpleXMLElement($xml);
registerNamespacesOnElement($sxe, $xmlns);
foreach ($result as $title) {
  echo $title . "<br>\n";


You Are a Spiritual Healer<br>