vicenrele
vicenrele

Reputation: 971

Reading XML with PHP. Not work (namespaces)

I can read XML files or strings but not the next:

$str = <<<XML
    <Output xmlns="nice.uniform://" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <Data i:nil="true"/>
        <Result xmlns:a="http://nice.uniform/CLSAPI3">
            <a:ResultCode>SUCCESS</a:ResultCode>
            <a:ResultMessage>OK</a:ResultMessage>
            <a:ResultCodeEx>CLS_SE_SUCCESS</a:ResultCodeEx>
        </Result> 
        <Exception i:nil="true" xmlns:a="http://schemas.datacontract.org/2004/07/System"/>
    </Output>
XML;

My PHP code to read a node of XML file is:

$Output = new SimpleXMLElement($str);
echo $Output->Result->{'a:ResultCodeEx'};

Also, I've tried:

$xmlResponse = simplexml_load_file('file.xml');
foreach($xmlResponse->Result as $xmlEntry)
{
 echo $xmlEntry->{'a:ResultCodeEx'};
}

//or

$blocks = $xmlResponse->xpath('//Output');
print_r($blocks);

Can you help me?

Upvotes: 1

Views: 52

Answers (1)

hek2mgl
hek2mgl

Reputation: 158270

The document uses several namespaces. The element ResultCodeEx belongs to the namespace a. You can use XPath, but you need to register the namespace a before the query:

$Output = new SimpleXMLElement($str);
$Output->registerXPathNamespace ('a', 'http://nice.uniform/CLSAPI3');
$result =  $Output->xpath('//a:ResultCodeEx/text()');
echo $result[0]; // CLS_SE_SUCCESS

Upvotes: 1

Related Questions