Parse SOAP response with namespaces in PHP [duplicate] - php

This question already has answers here:
parse an XML with SimpleXML which has multiple namespaces [duplicate]
(5 answers)
Closed 8 years ago.
Any recommendations how to parse this SOAP response and obtain the value of name for the report_type? Notice there are two instances of name; one under report_type and the other under severity.
Here is the SOAP response
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns1:getIRResponse xmlns:ns1="http://ws.icontent.idefense.com/V3/2">
<ns1:return xsi:type="ns1:IRResponse" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:report_type>
<ns1:id>0</ns1:id>
<ns1:name>Original Vulnerability</ns1:name>
</ns1:report_type>
<ns1:severity>
<ns1:id>0</ns1:id>
<ns1:name>HIGH</ns1:name>
</ns1:severity>
</ns:return>
</ns1:getIRResponse>
</soapenv:Body>
</soapenv:Envelope>
Here is the PHP code I'm using:
<?php
$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('ns1', 'http://ws.icontent.idefense.com/V3/2');
foreach ($xml->xpath('//ns1:report_type/name') as $item)
{
echo 'Name: '.$item,'<br>';
}
?>
The PHP code doesn't echo anything. When I use ($xml->xpath('//ns1:name') as $item) it returns both names (Original Vulnerability and HIGH).
I know I'm missing something stupid. Can you help please? Thank you in advance!

Firstly, I've corrected this element
</ns:return>
and changed it to
</ns1:return>
I seem to get the result you're after by duplicating the namespace prefix in both xpath segments
$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('ns1','http://ws.icontent.idefense.com/V3/2');
foreach ($xml->xpath('//ns1:report_type/ns1:name') as $item)
{
echo 'Name: '.$item,'<br>';
}
output
Name: Original Vulnerability

Related

How to convert an XML response from curl to json [duplicate]

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 4 months ago.
$response = curl_exec($ch);
curl_close($ch);
dd($response);
It is of type response string.
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns3:GetProductListResponse xmlns:ns3="http://xxx1">
<result>
<status>success</status>
</result>
<products>
<product>
<currencyAmount>900.00</currencyAmount>
<currencyType>1</currencyType>
<displayPrice>900.00</displayPrice>
<isDomestic>false</isDomestic>
<id>557830715</id>
<price>900.00</price>
<productSellerCode>TSRT7777</productSellerCode>
<approvalStatus>6</approvalStatus>
...
To convert this data to xml I used simplexml_load_string()
$response = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($response);
dd($xml);
And the output is like this.
^ SimpleXMLElement {#435}
I'm trying to access the data in it and try this.
$status = (string)$xml->result->status;
dd($status);
Returns :
^ ""
I tried using simplexml_load_file() and got no results. My main goal is to get this data as json, but I can't do it because I can't read the values.Any help would be great. Thanks in advance.
After #Jacob Mulquin's suggestion I used:
if ($xml === false) {
dump("b");
foreach (libxml_get_errors() as $error) {
dump($error->message);
}
dd("a");
} else {
dd("c");
}
Returned : "c"
Your sample xml is not well formed, for various reasons, but assuming that the actual $response is a well formed xml string, the following should get you what you need:
#first you need to deal with namespaces
$xml->registerXPathNamespace("ns3", "http://xxx1");
#then use xpath to select your target element
$status = $xml->xpath('//ns3:GetProductListResponse//status')[0];
echo $status;
Output should be
success

Get XML fields after SOAP call [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 3 years ago.
My asmx WEB service return this XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<PRODUCT>
<DESC>Vanilla ice cream</DESC>
<CODEERR>0</CODEERR>
</PRODUCT>
Calling WEB service from this PHP code
$SoapCli = new SoapClient('http://www.foo.com/MyService.asmx?WSDL');
$params = array(
'PARAM1' => 'some_param_1',
'PARAM2' => 'some_param_2',
);
$resp_WS = $SoapCli->__soapCall('MyFunction', array($params));
var_dump($resp_WS);
result is
object(stdClass)#11946 (1) {
["MyFunctionResult"]=>
object(stdClass)#11947 (1) {
["any"]=>
string(88) "<product xmlns=""><desc>Vanilla ice cream</desc><codeerr>0</codeerr></product>"
}
}
but, after googling a lot, I don't find PHP code for retreive values ​​of two fields DESC and CODER
You can use json_encode,json_decode,simplexml_load_string to parse the XML response, try the following code snippet to read the XML response
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<PRODUCT>
<DESC>Vanilla ice cream</DESC>
<CODEERR>0</CODEERR>
</PRODUCT>';
$res = json_decode(json_encode((array)simplexml_load_string($xml)),true);
Now you can use $res['DESC'] and $res['CODEERR'] to retrive the values.

Why does SimpleXML XPath return an empty array? [duplicate]

This question already has an answer here:
PHP simplexml: why does xpath stop working?
(1 answer)
Closed 8 years ago.
I've the following XML-File:
<SyncCustomerPartyMaster xmlns="http://schema.infor.com/InforOAGIS/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://schema.infor.com/InforOAGIS/2 http://schema.infor.com/2.9.1/InforOAGIS/BODs/Developer/SyncCustomerPartyMaster.xsd" releaseID="9.2" versionID="2.9.1">
<ApplicationArea>
<Sender>
<LogicalID>lid://infor.ln.dach_nausveln1_200</LogicalID>
<ComponentID>erp</ComponentID>
<ConfirmationCode>OnError</ConfirmationCode>
</Sender>
<CreationDateTime>2014-10-09T13:47:48Z</CreationDateTime>
</ApplicationArea>
<DataArea>
<Sync>
<TenantID>infor</TenantID>
<AccountingEntityID>200</AccountingEntityID>
<LocationID/>
<ActionCriteria>
<ActionExpression actionCode="Add"/>
</ActionCriteria>
</Sync>
<CustomerPartyMaster>
<PartyIDs>
<ID accountingEntity="200" lid="lid://infor.ln.dach_nausveln1_200" variationID="108">10100</ID>
<DisplayID>10100</DisplayID>
</PartyIDs>
</CustomerPartyMaster>
</DataArea>
</SyncCustomerPartyMaster>
And I'm trying to access the DisplayId via XPath: '/SyncCustomerPartyMaster/DataArea/CustomerPartyMaster/PartyIDs/DisplayID'
<?php
$xml = simplexml_load_file("example.xml");
$displayId = $xml->xpath('/SyncCustomerPartyMaster/DataArea/CustomerPartyMaster/PartyIDs/DisplayID');
print_r($xml);
echo '<br />';
echo '<br />';
print_r($displayId);
?>
But print_r($display_id) just returns an empty array. I fiddled around a bit with registerXPathNamespace]1 which did not do the trick - can anyone please point me into the right direction?
xmlns="http://schema.infor.com/InforOAGIS/2"
This declares a default namespace which you do need to register via registerXPathNamespace() and address the elements using the prefix registered.
Example:
$xml = simplexml_load_file("example.xml");
$xml->registerXPathNamespace('ns', "http://schema.infor.com/InforOAGIS/2");
$displayIds = $xml->xpath('/ns:SyncCustomerPartyMaster/ns:DataArea/ns:CustomerPartyMaster/ns:PartyIDs/ns:DisplayID');
foreach ($displayIds as $displayId) {
echo $displayId;
}
Output:
10100

Parsing XML with namespace information [duplicate]

This question already has answers here:
SimpleXML SOAP response Namespace issues
(2 answers)
Closed 8 years ago.
I found lot of solutions for this problem, but my code won't work!
XML INFO:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:resultado xmlns:ns2="http://webservice.consulta.spcjava.spcbrasil.org/" data="2014-06-03T11:37:32.001-03:00" restricao="false">
<protocolo digito="2" numero="1204248496" />
.... other XML info
MY CODE:
$s = '<?xml version="1.0" encoding="UTF-8"?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:resultado xmlns:ns2="http://webservice.consulta.spcjava.spcbrasil.org/" data="2014-06-03T11:37:32.001-03:00" restricao="false"><protocolo digito="2" numero="1204248496" /> ...
$xml = simplexml_load_string($s);
$x2 = $xml->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://webservice.consulta.spcjava.spcbrasil.org/')->resultado->protocolo->digito;
print_r($x2);
var_dump(count($x2));
Returns null and 0 for the object count.
I've been following this tutorial: http://amigotechnotes.wordpress.com/2013/11/16/parse-xml-with-namespace-by-simplexml-in-php/
I don't get where my example differs from his example. :/
Can anyone help me with this issue, please?
Finally made it work using another syntax.
$xml = simplexml_load_string($resultadoDocumento[0]["cdo_xml"]);
$resultadoSPC = $xml->children('S', TRUE)->Body->children('ns2', TRUE)->children();
accessing nodes by:
<?php foreach ($resultadoSPC->consumidor->children()->{"consumidor-pessoa-fisica"} as $consumidorElement) : ?>
<?php echo $consumidorElement->attributes()->{"nome"}; ?>

Linked in xml response to php variables [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 9 years ago.
i am getting this result from my linked in connect script,
<person>
<email-address>xzenia1#gmail.com</email-address>
<picture-url>http://m3.licdn.com/mpr/mprx/0_UiHHf6SiF4yuBerHUkfUfkshFpomUIrHMbpBf5Iy4sOYk7FecL4XTLxtdAEl42AXsho9hGzDtRBl</picture-url>
</person>
this is the php call
$xml_response = $linkedin->getProfile("~:(email-address,picture-url)");
how to make them assign to separate PHP variable.
You can load your xml as string with simplexml_load_string and then loop in it to get all data
$xml = simplexml_load_string($xml_response);
foreach($xml as $key => $val)
{
echo "$key=>$val<br>" . "\n";
}
This will output
email-address=>xzenia1#gmail.com
picture-url=>http://m3.licdn.com/mpr/mprx/0_UiHHf6SiF4yuBerHUkfUfkshFpomUIrHMbpBf5Iy4sOYk7FecL4XTLxtdAEl42AXsho9hGzDtRBl
Live sample
Try,
$xml = (array)simplexml_load_string($xml_response);
echo $email=$xml['email-address'];
echo $picture=$xml['picture-url'];
$xml = simplexml_load_string($linkedin->getProfile("~:(email-address,picture-url)"));
echo $xml->{'email-address'}[0] . "<br />";
echo $xml->{'picture-url'}[0];
simplexmldoesn't like - in node names, therefore use $xml->{'email-address'} instead of $xml->email-address.
use index [0] on both nodes, just in case, if one day your simplexml object would contain more than one <person> node...
see it working: http://codepad.viper-7.com/dQQ6sa

Categories