Parse Soap XML Response - php

I need to parse the following XML response:
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"><SOAP:Body><m:LoginResponse xmlns:m="http://www.e-courier.com/schemas/" UserGUID="{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" UserID="1" LoginGUID=""/></SOAP:Body></SOAP:Envelope>
I need to get the UserGUID, so I created the following peace of code:
$xmlResponse = $client->__doRequest($xml_request, $this->__url_request, "XML", SOAP_1_1);
$xml = simplexml_load_string($xmlResponse);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('m', 'http://www.e-courier.com/schemas/');
foreach ($xml->xpath('//LoginResponse') as $a)
{
error_log(print_r($a));
}
The problem is that I never get anything printed on the error_log.
What am I doing wrong?
Edit: I found out that $xml is not being created successfully... Should I use something before calling simplexml_load_string?

Related

Webhook XML always empty

I'm using recurly webhooks to update contacts, but the XML is always empty, here's what I've tried:
$xmlString = file_get_contents('php://input');
$dom = new DomDocument();
$dom->loadXML($xmlString);
however when I look into the file, it is always empty:
$rsn = $dom->getElementsByTagName('successful_payment_notification');
if($rsn->length != 0){
//.. do something
}
but I've noticed that the $dom is always empty, here's what the XML recurly sends:
<?xml version="1.0" encoding="UTF-8"?>
<successful_payment_notification>
<account>
<account_code>89728427a3caa0b21b2ds31223c0fad6f443b82</account_code>
<first_name>Michael</first_name>
<last_name>Scott</last_name>
<company_name nil="true"></company_name>
<phone nil="true"></phone>
</account>
<transaction>
<id>467fc116288ab89c8d7c954bbca565a8</id>
<invoice_id>467fc11613dcd438d4410c4ca0bc03e8</invoice_id>
<invoice_number_prefix></invoice_number_prefix>
<invoice_number type="integer">1379</invoice_number>
<test type="boolean">false</test>
<voidable type="boolean">false</voidable>
<refundable type="boolean">true</refundable>
</transaction>
</successful_payment_notification>
allow_url_fopen is On, not sure what could be causing this, I'm using AWS Lightsail and Bitnami.
I've found the answer, I changed it to this:
$xml = new SimpleXMLElement(file_get_contents('php://input'));
$data = json_decode(json_encode($xml), true);
switch ($xml->getName()) {
case "renewed_subscription_notification":
sendEmail("renewed_subscription_notification");
break;
}

How to convert SOAP API response from XML to JSON

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetCategoriesJsonResponse xmlns="http://tempuri.org/">
<GetCategoriesJsonResult>[{"code":"0","description":"Sides","storeNumber":"3733"},{"code":"1","description":"Sandwiches","storeNumber":"3733"},</GetCategoriesJsonResult>
</GetCategoriesJsonResponse>
</s:Body>
</s:Envelope>
That is the result of the API, but I want to convert it like:
[
{
"code": "0",
"description": "Sides",
"storeNumber": "3733"
},
{
"code": "1",
"description": "Sandwiches",
"storeNumber": "3733"
},
]
How can I do this? I've tried json_encode and json_decode but it didn't work for me. I have applied different methods to convert it but it's still showing XML results. Can anyone tell me how I can convert it into JSON?
Here's a good answer on available options to working with xml https://stackoverflow.com/a/3577662/3266626
I use FluentDom
$xml = file_get_contents("xml_file.xml");
$doc = new DOMDocument();
$doc->loadXML($xml);
$json = new \FluentDOM\Serializer\Json\RabbitFish($doc);
$object = json_decode($json);
echo "<pre>" . print_r( $object, true) . "</pre>";
echo "<script>console.log({$json})</script>";
Edit: replaced
// PHP Deprecated: Non-static method DOMDocument::loadXML() should not be called statically
$doc = DOMDocument::loadXML($xml);
with
$doc = new DOMDocument();
$doc->loadXML($xml);
I found the solution on that link thanks guys for helping
using api response in this way helps me alot
How to convert SOAP response to PHP Array?
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//sBody')[0];
$array = json_decode(json_encode((array)$body), TRUE);
This code is perfectly done thing into JSON
First parse xml and convert data to array:
$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];

Specific field from XML into PHP

I am pretty new to XML sheets in combination with PHP. I am trying to pull data from an XML file that is being returned to me via SOAP call.
My XML is being returned as this.
commented out some of the details
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<loginResponse>
<result>
<metadataServerUrl>https://...-api.salesforce.com/service...</metadataServerUrl>
<passwordExpired>false</passwordExpired>
<sandbox>false</sandbox>
<serverUrl>https://...--api.salesforce.com/services/Soap/u/21.0/0...</serverUrl>
<sessionId>....</sessionId>
<userId>....</userId>
<userInfo>
<accessibilityMode>false</accessibilityMode>
<currencySymbol>€</currencySymbol> ... </userInfo>
</result>
</loginResponse>
</soapenv:Body>
</soapenv:Envelope>
So I am trying to pull out of this the sessionID
// UP HERE SOAP CALL --- return data
.......
} else {
$response = curl_exec($soap_do);
curl_close($soap_do);
// print($response); <-- see result XML
// grabbing the sessionid
$xmlresponse = new SimpleXMLElement($response);
$test = $xmlresponse->result->sessionId['value'];
echo $test;
}
This returns blank, but when I start adding the LoginResponse and the Soapenv (body and envelope), i get an error about that I am trying to get a propperty of non-object. I am not sure what I am doing wrong here.
With SimpleXML you can use SimpleXMLElement::children to find children by an XML namespace (here soapenv).
For your case it would something like
$xmlresponse = new SimpleXMLElement($response);
$response = $xmlresponse->children('soapenv', true)->Body->children('', true)->loginResponse->result->sessionId;
var_dump($response);
Which results in
object(SimpleXMLElement)#4 (1) {
[0]=>
string(4) "...."
}
I want to say that you should use SoapClient(http://php.net/manual/tr/class.soapclient.php) for Soap Calls but if you don't want to use it, here is how you can parse this XML :
$xmlresponse = new SimpleXMLElement(str_ireplace([':Envelope', ':Body'], '', $response));
$test = $xmlresponse->soapenv->loginResponse->result->sessionId['value'];
echo $test;

Can't get data from XML with namespaces

I make a soap request and I get the following response:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://*************/******/****" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://*************/******/****/***">
<SOAP-ENV:Body>
<ns1:GetEventV2Response>
<ns1:GetEventV2Result>
<ns1:Events>
<ns1:Event>
<ns1:Id>147624</ns1:Id>
<ns1:Name>Rockstars</ns1:Name>
<ns1:Genre>
...
I have tried to get the element ID inside of <ns1:Event>, but the code bellow doesn't work and don't know why. I searched and tried a fews solutions but without success.
header("Content-type: text/xml");
....
$response = curl_exec($ch);
curl_close($ch);
x = new SimpleXmlElement($response);
foreach($x->xpath('//ns1:Event') as $event) {
var_export($event->xpath('ns1:Id'));
}
why don't you try this?
$xml = simplexml_load_string($xml);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
foreach ($xml->xpath('//ns1:Event') as $item)
{
print_r($item);
}
http://php.net/manual/en/function.simplexml-load-string.php
Use SimpleXMLElement::registerXPathNamespace to register the namespace. For example:
$x->registerXPathNamespace('ns1', 'http://*************/******/****');
and, later:
$event->registerXPathNamespace('ns1', 'http://*************/******/****');

Empty xml object when using SimpleXML - Node no longer exists

The xml is as follows:
<root>
<organizations>
<organization>
<info>
<orgID>1234</orgID>
<orgName>XYZ Company</orgName>
<address>
<address1>1 Main Street</address1>
<city>Somewhere</city>
<state>MI</state>
<zip>12334</zip>
</address>
</info>
</organization>
</organizations>
</root>
The code is as follows:
$ind = strpos($xmlResponse, "<");
$xml = simplexml_load_string(substr($xmlResponse, $ind));
//echo $xml;
$orgList = $xml->organizations->children();
foreach($orgList as $orgList)
{
echo $orgList->orgName;
}
And I get the following error:
Warning: main() [function.main]: Node no longer exists in...
The offending line is
foreach($orgList as $orgList)
Can anyone tell me what I'm doing wrong? I've tried accessing the xml through 50 different ways and either get that error or an empty xml object.
Thanks in advance!
It looks like you're overwriting the xml object when you loop with $orgList as $orgList. Try this instead:
foreach($orgList as $org)
echo $org->orgName;
Try the following:
$xml = simplexml_load_string($xml);
$org = $xml->organizations->children();
foreach($org as $k => $v)
{
echo $v->info->orgName;
}
Try using xpath
Put the XML in x.xml file
then create php file:
<?php
$xml = simplexml_load_file('x.xml');
$orgList = $xml->xpath("/root/organizations/organization/info");
print $orgList[0]->orgName;
?>

Categories