This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 8 years ago.
I have the following xml file:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:doTransactionResponse xmlns:ns2="http://soap.api.controller.web.payjar.com/">
<return>
<displayMessage>An error occurred with this payment, please contact your merchant (ref: P022)</displayMessage>
<merchantReference>mercRef_1350047403</merchantReference>
<payUReference>11999149347</payUReference>
<pointOfFailure>PAYU</pointOfFailure>
<resultCode>P022</resultCode>
<resultMessage>Transaction is not in the correct state - last transaction: FINALIZE state: SUCCESSFUL</resultMessage>
<successful>false</successful>
</return>
</ns2:doTransactionResponse>
</soap:Body>
</soap:Envelope>
I need to test the result code in the xml file against a series of codes. How would I get the specific element value of <resultCode> using PHP?
DOMDocument in combination with getElementsByTagName would be a quick solution.
DOMDocument::getElementsByTagName
$xml_string = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:doTransactionResponse xmlns:ns2="http://soap.api.controller.web.payjar.com/">
<return>
<displayMessage>An error occurred with this payment, please contact your merchant (ref: P022)</displayMessage>
<merchantReference>mercRef_1350047403</merchantReference>
<payUReference>11999149347</payUReference>
<pointOfFailure>PAYU</pointOfFailure>
<resultCode>P022</resultCode>
<resultMessage>Transaction is not in the correct state - last transaction: FINALIZE state: SUCCESSFUL</resultMessage>
<successful>false</successful>
</return>
</ns2:doTransactionResponse>
</soap:Body>
</soap:Envelope>';
$dom = new DOMDocument;
$dom->loadXML($xml_string);
$nodes = $dom->getElementsByTagName('resultCode');
foreach ($nodes as $node) {
echo $node->nodeValue;
}
Result: P022
Of course there are several other ways to work with XMLs in PHP (xpath etc.)
Using xpath. Here's the code as mentioned by KURN,
<?php
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:doTransactionResponse
xmlns:ns2="http://soap.api.controller.web.payjar.com/">
<return>
<displayMessage>An error occurred with this payment, please contact
your merchant (ref: P022)</displayMessage>
<merchantReference>mercRef_1350047403</merchantReference>
<payUReference>11999149347</payUReference>
<pointOfFailure>PAYU</pointOfFailure>
<resultCode>P022</resultCode>
<resultMessage>Transaction is not in the correct state - last
transaction: FINALIZE state: SUCCESSFUL</resultMessage>
<successful>false</successful>
</return>
</ns2:doTransactionResponse>
</soap:Body>
</soap:Envelope>
';
$xml = simplexml_load_string($xml, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('soapenv', 'http://schemas.xmlsoap.org/soap/envelope/');
foreach($xml->xpath('//soapenv:Body') as $header)
{
$arr = $header->xpath('//resultCode'); // Should output 'something'.
$resultCode = $arr[0];
echo $resultCode;// outputs P022
}
?>
Actually this is quite easy with PHP:
$resultCode = simplexml_load_string($xml_string)->xpath('//resultCode')[0];
var_dump((string) $resultCode); // string(4) "P022"
Note that this code has no error checking, it might fatal-error in case the XML can not be loaded and warnings/notices if the element you're looking for does not exist at least once.
Related
This question already has answers here:
SimpleXMLElement Access elements with namespace?
(4 answers)
Closed 1 year ago.
echo $xml->asXML();
Prints the following, and I am tring to access to elements here like: InvoiceStateResult
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<soap:Header>
<wsa:Action>http://tempuri.org/SendEArchiveDataResponse</wsa:Action>
<wsa:MessageID>urn:uuid:72e8aaf0-b36d-422f-ab0b-486c17c50c83</wsa:MessageID>
<wsa:RelatesTo>urn:uuid:fc0a3e9d-40c1-4f3b-9517-8002825b7217</wsa:RelatesTo>
<wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
<wsse:Security>
<wsu:Timestamp wsu:Id="Timestamp-3a82271a-a910-4062-81aa-984468387047">
<wsu:Created>2021-05-28T12:12:23Z</wsu:Created>
<wsu:Expires>2021-05-28T12:27:23Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</soap:Header>
<soap:Body>
<SendEArchiveDataResponse
xmlns="http://tempuri.org/">
<SendEArchiveDataResult>
<Invoices>
<InvoiceStateResult>
<ServiceResult>Error</ServiceResult>
<UUID>11111111-2222-3333-4444-555555555555</UUID>
<InvoiceId>T612014000000053</InvoiceId>
<StatusDescription>INVOICE EXISTS</StatusDescription>
<StatusCode>29</StatusCode>
<ErrorCode>0</ErrorCode>
<ReferenceNo>T612014000000053</ReferenceNo>
</InvoiceStateResult>
</Invoices>
<ServiceResult>Error</ServiceResult>
<ServiceResultDescription>This invoice processed before InvoiceId : TRL2021000000019 , UUID : DB3642EB-7A5F-40FD-8DF8-A922CA113837 SenderTaxID : 3324502175 . </ServiceResultDescription>
<Source>IntegrationWebService</Source>
<ErrorCode>30</ErrorCode>
<invoiceCount>1</invoiceCount>
</SendEArchiveDataResult>
</SendEArchiveDataResponse>
</soap:Body>
</soap:Envelope>
However I couldn't reach any of the nodes. I tried this:
foreach($xml->children() as $child) {
echo "Child node: " . $child . "</br>";
}
and it returns empty.
How will I access the nodes ?
Thanks
Simple XML, is - as the name suggests, a very simple implementation and it looks for standard namespaces. You can use registerXPathNamespace to look for non custom ones. See example below that works for your code.
$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
print_r($xml->xpath('//soap:Body')[0]->SendEArchiveDataResponse->SendEArchiveDataResult->Invoices->InvoiceStateResult);
This question already has answers here:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
(2 answers)
Closed 2 years ago.
my xml not parsing, i have no idea why
First line of xml not parsing, but second line parsing good
I know about im missings whatever in code, but searched in google and not find correct answer for it
// this xml not work, with <soap:Envelope> tags
$string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetBrandsListResponse xmlns="http://tempuri.org/">
<GetBrandsListResult>
<DocumentElement>
<BrandLst>
<ID>1</ID>
<Name>Audi</Name>
</BrandLst>
<BrandLst>
<ID>350</ID>
<Name>BMW</Name>
</BrandLst>
</DocumentElement>
</GetBrandsListResult>
</GetBrandsListResponse>
</soap:Body>
</soap:Envelope>';
// but this xml works, without soap envelope tags
$string = '
<BrandLst>
<ID>1</ID>
<Name>Audi</Name>
</BrandLst>
';
$xml = simplexml_load_string($string);
var_dump($xml);
Fixed with adding xpath and registerXPathNamespace
$xml = simplexml_load_string($string);
$xml->registerXPathNamespace('default', 'http://tempuri.org/');
$auto = $xml->xpath("//default:BrandLst");
I've been trying to figure this out for over an hour now, and I give up. I'm getting the following response from a webservice.
I want to be able to get access to the children of Fault (I have this working for another webservice call, but for some reason, which I believe MIGHT be namespace related, this one doesn't work).
<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Invalid Scope</faultstring>
<detail>
<faultresponse xmlns="xsd url" xmlns:ns2="xsd url">
<transactionid>TEST</transactionid>
<errorcode>ERR-4223</errorcode>
</faultresponse>
</detail>
</soap:Fault>
</soap:Body>
</soap:envelope>
My PHP code is pretty simple. Firstly, I create the SimpleXmlElement object from the above xml.
I get a list of namespaces in the xml (which it picks up two: "soap", and ""). I then get the children of the XML in the soap: namespace.
$xml = simplexml_load_string($response_xml);
$namespace = $xml->getNamespaces(true);
$soap = $xml->children($namespace['soap']);
Given the above code. I would expect to be able to do something like this:
$fault_fields = $soap->Body->children()->Fault->children();
foreach ($fault_fields as $field):
echo (string) $field->getName() . ' - ' . $field[0] . '<br />';
endforeach;
However, if I run $soap->asXML(); I can see the following:
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Invalid Scope</faultstring>
<detail>
<faultresponse xmlns="xsd url" xmlns:ns2="xsd url">
<transactionid>TEST</transactionid>
<errorcode>ERR-4223</errorcode>
</faultresponse>
</detail>
</soap:Fault>
</soap:Body>
But if I try to go to access Body or Fault:
$soap = &$this->parse_soap_body($response_xml);
$body = $soap->Body->children()->Fault->children();
echo $body->asXML();
I get a Node no longer exists error with the stack returning this XML.
<soap:Envelope xmlns:soap="`http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Invalid Scope</faultstring>
.... more xml
This is seriously doing my head in.
Any help would be greatly appreciated.
SO,
I'm receiving the following SOAP response as a string:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<GetListItemsResult>
<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
<rs:data ItemCount="3">
<z:row ows_DocIcon="jpg" ows_LinkFilename="18380014229851.jpg" ows_Modified="2016-10-08 17:27:40" ows_Editor="179440;#asdf" ows_Last_x0020_Modified="2;#2016-10-08 17:29:29" ows_ID="2" ows_Created_x0020_Date="2;#2016-10-08 17:27:40" ows_FileLeafRef="2;#18380014229851.jpg" />
<z:row ows_DocIcon="jpg" ows_LinkFilename="18380014229851_2.jpg" ows_Modified="2016-10-08 17:27:40" ows_Editor="179440;#asfd" ows_Last_x0020_Modified="3;#2016-10-08 17:29:29" ows_ID="3" ows_Created_x0020_Date="3;#2016-10-08 17:27:41" ows_FileLeafRef="3;#18380014229851_2.jpg" />
<z:row ows_DocIcon="jpg" ows_LinkFilename="18380014229851_3.jpg" ows_Modified="2016-10-08 17:27:40" ows_Editor="179440;#asdf" ows_Last_x0020_Modified="4;#2016-10-08 17:30:03" ows_ID="4" ows_Created_x0020_Date="4;#2016-10-08 17:27:41" ows_FileLeafRef="4;#18380014229851_3.jpg" />
</rs:data>
</listitems>
</GetListItemsResult>
</GetListItemsResponse>
</soap:Body>
</soap:Envelope>
I am attempting to get each of the "z:row" entries, but am struggling due to the namespaces (after some googling that's what i'm understanding them to be called).
Here is the code I am using:
$xml = simplexml_load_string($sp->soapClient->__last_response);
foreach($xml->GetListItemsResult as $item)
{
$ns_li = $item->children('uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882');
$ns_rs = $ns_li->children('urn:schemas-microsoft-com:rowset');
$ns_z = $nr_rs->children('#RowsetSchema');
echo $ns_z->row;
}
Right now I am getting no output from echo statement. What am I doing wrong?
You can use XPath expression to get specific part of XML document using various criteria. For example, to get z:row elements anywhere in the XML document you can simply do //z:row, after registering the prefix z :
$xml->registerXPathNamespace("z", "#RowsetSchema");
foreach($xml->xpath('//z:row') as $item)
{
echo $item["ows_LinkFilename"] ."\n";
}
eval.in demo
output :
18380014229851.jpg
18380014229851_2.jpg
18380014229851_3.jpg
So I'm getting an xml file back from a soap service (of which I have no control over). It's returning back an xmlns which is causing simpleXML issues. I'm running a str_replace to get rid of that issue, however now simpleXML just returns an empty object. XML structure appears to be fine, no errors just an empty object.
$xmlString = $client->__getLastResponse();
$feed = str_replace(' xmlns="LMSWebservice"', '', $xmlString);
$sData= simplexml_load_string($feed);
print_r($sData);
Returns: SimpleXMLElement Object()
XML source before str replace is:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetUserInternalIDByPersonalIDResponse xmlns="LMSWebservice">
<GetUserInternalIDByPersonalIDResult>
<Response xmlns="">
<Timestamp date="24/10/2013" time="04:27:37" />
<User>
<UserInternalID>4907</UserInternalID>
</User>
</Response>
</GetUserInternalIDByPersonalIDResult>
</GetUserInternalIDByPersonalIDResponse>
</soap:Body>
</soap:Envelope>
After str replace:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetUserInternalIDByPersonalIDResponse>
<GetUserInternalIDByPersonalIDResult>
<Response xmlns="">
<Timestamp date="24/10/2013" time="04:27:37" />
<User>
<UserInternalID>4907</UserInternalID>
</User>
</Response>
</GetUserInternalIDByPersonalIDResult>
</GetUserInternalIDByPersonalIDResponse>
</soap:Body>
</soap:Envelope>
Any help would be greatly appreciated, this is driving me crazy!
----So if I don't get rid of the namespace attribute I get this error message:
Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser warning : xmlns: URI LMSWebservice is not absolute in serviceTest2.php on line 16
Warning: simplexml_load_string() [function.simplexml-load-string]: LSchema"><soap:Body><GetUserInternalIDByPersonalIDResponse xmlns="LMSWebservice" in serviceTest2.php on line 16
Warning: simplexml_load_string() [function.simplexml-load-string]: ^ in serviceTest2.php on line 16
If I try using xPath to get at UserInternalID it returns an empty array. If what you're saying is correct and this is going into simpleXML correctly, then how do I access the UserInternalID node? Sorry, this is the first time using simpleXML and this is just perplexing me.
So just tried changing the NS
$feed = str_replace('xmlns="LMSWebservice"', 'xmlns="ns:LMSWebservice"', $xmlString);
which goes in without errors.
I tried this for the xPath
$ID = $sData->xpath('UserInternalID');
I understand this is probably completely wrong, but I haven't tried much else with this as it didn't seem to be going into simpleXML correctly in the first place. :/
So I've used
$ID = $sData->xpath('//UserInternalID');
echo $ID[0];
Which works perfectly. Thank you for all your help!
Through the extensive comments and your last edit finally the actual cause of your problem could be revealed, the xpath expression is wrong:
$ID = $sData->xpath('UserInternalID');
Wrong with it is the path, this matches no elements. Instead you could use:
$ID = (string) $xml->xpath('//UserInternalID')[0];
Or more verbose:
$ID = (string) $xml->xpath('//Response/User/UserInternalID')[0];
Key point here is that you write the correct path to the element you would like to query for.
Complete usage example:
<?php
/**
* SoapClient xml return string with simpleXML
*
* #link http://stackoverflow.com/q/19556414/367456
*/
$response = <<<RESPONSE
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetUserInternalIDByPersonalIDResponse xmlns="LMSWebservice">
<GetUserInternalIDByPersonalIDResult>
<Response xmlns="">
<Timestamp date="24/10/2013" time="04:27:37" />
<User>
<UserInternalID>4907</UserInternalID>
</User>
</Response>
</GetUserInternalIDByPersonalIDResult>
</GetUserInternalIDByPersonalIDResponse>
</soap:Body>
</soap:Envelope>
RESPONSE;
$restore = libxml_use_internal_errors(TRUE);
$xml = simplexml_load_string($response);
libxml_use_internal_errors($restore);
echo $xml->xpath('//Response/User/UserInternalID')[0];
Output:
4907
Online Demo: https://eval.in/57149
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($response);
libxml_clear_errors();
$xml = $doc->saveXML($doc->documentElement);
$xml = simplexml_load_string($xml);
Use this helped me in a big way.