Reputation: 553
I want to access the XML and parse it as JSON.
<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ser='http://service.billing.org/'>
<soapenv:Header />
<soapenv:Body>
<ser:processTrans>
<xmlValue>
<![CDATA[
<ebpacket>
<head>
<packettype> UserAuthorization</packettype>
<staffcode> ePay_UserName </staffcode>
<pwd> ePay_Password </pwd>
</head>
<body>
<email> _username </email>
<loginpwd> _password </loginpwd>
<deviceid> DeviceId </deviceid>
</body>
</ebpacket>
]]>
</xmlValue>
</ser:processTrans>
I am able to access the values the following way:
$xml_str = str_replace(PHP_EOL, '', $xmlstr);
$xml = SimpleXML_Load_String($xml_str,'SimpleXMLElement', LIBXML_NOCDATA, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('ser', 'http://service.billing.org');
$j_obj = json_encode($xml->xpath('//soapenv:Body'));
The problem is that, XML structure is not known in advance. Hence, I cannot specifically access through the namespace. Unless I specify the namespace $xml->xpath('//soapenv:Body'), it does not return the expected result.
Upvotes: 0
Views: 1912
Reputation: 57121
I think your getting the two namespaces mixed up, your trying to register the soapenv
prefix with the URI used for ser
. Not that this affects the code, but it may not give what your expecting.
As for not knowing the namespaces in advance, in SimpleXML you can use getDocNamespaces()
to fetch the namespaces from the document and then loop through and register them against the prefixes. So the following code fetches the XML content of the Body...
$xml_str = str_replace(PHP_EOL, '', $xmlstr);
$xml = simplexml_load_string($xml_str,'SimpleXMLElement', LIBXML_NOCDATA);
$ns = $xml->getDocNamespaces(true);
foreach ( $ns as $prefix => $URI ) {
$xml->registerXPathNamespace($prefix, $URI);
}
$j_obj = json_encode($xml->xpath('//soapenv:Body/*'));
Upvotes: 2