print xml response separately for each property - php

I am trying to convert this XML to array this is the response I am getting from API and I want to get the value of statuscode but I am unable to do it.
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
but when i am using the following code
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'RequestData='.$post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
$resultres=xml2ary($result);
echo '<pre>';
print_r($resultres);
The output is
Array
(
[string] => Array
(
[_a] => Array
(
[xmlns] => http://tempuri.org/
)
[_v] => 201234
)
)
How is the result changing? I have used one more technique also but with that also I am not getting the result that is required

Have a look at SimpleXML
<?php
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'RequestData='.$post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
/** #var SimpleXMLElement $xml */
$xml = simplexml_load_string($result);
// nice, use SimpleXMLElement object
var_dump($xml);
// not nice, use array instead
var_dump((array) $xml);
Just make sure the XML response you're getting from the API is the same you have posted above. Here it is again for reference:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
Here is an example without cURL, just add it to a file and run it from the terminal:
<?php
$xmlString = <<<XML
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
XML;
$xml = simplexml_load_string($xmlString);
// everything
var_dump($xml);
// independent values
var_dump((string) $xml->STATUSCODE);
var_dump((string) $xml->STATUS);
// now with arrays
$array = (array) $xml;
// everything
var_dump($array);
// independent values
var_dump($array['STATUSCODE']);
var_dump($array['STATUS']);
// want to print it?
echo sprintf('Registration responded with status code %d and status %d', $xml->STATUSCODE, $xml->STATUS) . PHP_EOL;
echo sprintf('Registration responded with status code %d and status %d', $array['STATUSCODE'], $array['STATUS']) . PHP_EOL;

If the XML is coming through, for instance like so:
<class>
<type>
<input>Text</input>
<input>Text</input>
</type>
<type>
<input>Text</input>
<input>Text</input>
</type>
<type>
<input>Text</input>
<input>Text</input>
</type>
</class>
What you could do is:
$xml = simplexml_load_file("filepath");
$classes = $xml->$class;
foreach ($classes as $keyClass => $class) {
echo "<ul><li>Class</li><ul>";
$types = $class->type;
foreach ($types as $keyType => $type) {
echo "<li>Type</li><ul>";
$inputs = $type->input;
foreach ($inputs as $keyInput => $input) {
echo "<li>Input</li>";
}
echo "</ul>";
}
echo "</ul></ul>";
}

Related

Assist with USPS API using PHP Curl

Hello I am trying to do API call to USPS API using PHP Curl.
I get the following response:
[Number] => 80040B19
[Description] => XML Syntax Error: Please check the XML request to see if it can be parsed.
[Source] => USPSCOM::DoAuth
I put together my code for the API call from some sample code on here and also the sample on the USPS site; but cannot get it to work (getting error above); here is my code:
$input_xml = '<AddressValidateRequest USERID="xxxxxxx">
<Address ID="0">
<Address1></Address1>
<Address2>6406 Ivy Lane</Address2><City>Greenbelt</City>
<State>MD</State>
<Zip5></Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>';
$url = "http://production.shippingapis.com/ShippingAPITest.dll?API=Verify";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
I am hoping someone can help with what I am doing wrong...
According to the documentation, you're supposed to pass the XML in a field named XML, not xmlRequest. Try something like this instead:
<?php
$input_xml = <<<EOXML
<AddressValidateRequest USERID="xxxxxxx">
<Address ID="0">
<Address1></Address1>
<Address2>6406 Ivy Lane</Address2>
<City>Greenbelt</City>
<State>MD</State>
<Zip5></Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>
EOXML;
$fields = array(
'API' => 'Verify',
'XML' => $input_xml
);
$url = 'http://production.shippingapis.com/ShippingAPITest.dll?' . http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
// Convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
?>

Parse XML SOAP response php

I'm using the following code to send an request to a SOAP service:
header('Content-type: application/xml');
function doXMLCurl($url,$postXML){
$CURL = curl_init();
curl_setopt($CURL, CURLOPT_URL, $url);
curl_setopt($CURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($CURL, CURLOPT_POST, 1);
curl_setopt($CURL, CURLOPT_POSTFIELDS, $postXML);
curl_setopt($CURL, CURLOPT_HEADER, false);
curl_setopt($CURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($CURL, CURLOPT_HTTPHEADER, array('Accept: text/xml','Content-Type: application/soap+xml'));
curl_setopt($CURL, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec($CURL);
return $xmlResponse;
}
$input_xml = '<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">.....</s:Envelope>';
echo doXMLCurl('webservice_url', $input_xml);
The responde is a XML too.
How can i parse this data or convert to an array or object? I tried with simplexml_load_string() but without success.
EDIT
XML Response:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">...</a:Action>
</s:Header>
<s:Body>
<ListStatesResponse xmlns="http://tempuri.org/">
<ListStatesResult xmlns:b="..." xmlns:i="...">
<b:Return>0</b:Return>
<b:Message i:nil="true"/>
<b:Status>00</b:Status>
<b:ListStates>
<b:States>
<b:Description>ACRE</b:Description>
<b:Code>AC</b:Code>
</b:States>
<b:States>
<b:Description>ALAGOAS</b:Description>
<b:Code>AL</b:Code>
</b:States>
<b:States>
<b:Description>AMAZONAS</b:Description>
<b:Code>AM</b:Code>
</b:States>
...
</b:ListStates>
</ListStatesResult>
</ListStatesResponse>
</s:Body>
</s:Envelope>
Assuming the xml is valid, you can use SimpleXMLElement, i.e.:
$xml = new SimpleXMLElement($xmlResponse);
echo $xml->node->otherNode['Id'];
To loop it, use:
foreach ($xml->node->otherNode as $el) {
foreach($el as $key => $val) {
echo "{$key}: {$val}";
}
}
I found the easiest way is to use json functions
$jsonObject = json_decode(json_encode($xmlString));
Then print_r($jsonObject) to find the structure. This allows attributes to be accessible to using $jsonObject->{'#attributes'}->id;

PHP cURL & Blackboard Learn - Data is not correct.... POX Data Content is not allowed in prolog

When I try to POST this XML document to Blackboard Learn LIS using PHP cURL I get this error. I'm checking the XML with simplexml to ensure it is well formed, so that's not the issue. I have also checked the XML document to ensure there is no BOM data attached. I've opened it in a Hex editor to ensure this.
I'm completely stumped on this one and I don't have access to the Blackboard logs.
PHP:
include("xml/envelope.php");
//sanity check to see if xml is well formed
$sxml = simplexml_load_string($xml);
$xml = $sxml->asXML();
$xml_length = strlen($xml);
$url = $this->lis_outcome_service_url;
$bodyHash = base64_encode(sha1($xml, TRUE)); // build oauth_body_hash
$consumer = new OAuthConsumer($key, $secret);
$request = OAuthRequest::from_consumer_and_token($consumer, '', 'POST', $url, array('oauth_body_hash' => $bodyHash) );
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, '');
$header = $request->to_header() . "Content-Type: application/xml\r\nContent-Length: $xml_length\r\n"; // add content type header
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$output .= "$url<br><br>$output<pre>$header\n\n".htmlspecialchars($xml)."</pre><p>ERRORS?: ".curl_error($ch);
curl_close($ch);// "<p>Saved grade: "+var_export($output)+"</p>";
return $output;
The XML in envelope.php:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
<imsx_POXHeader>
<imsx_POXRequestHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>$id</imsx_messageIdentifier>
</imsx_POXRequestHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
<replaceResultRequest>
<resultRecord>
<sourcedGUID>
<sourcedId>$this->lis_result_sourcedid</sourcedId>
</sourcedGUID>
<result>
<resultScore>
<language>en-us</language>
<textString>0.7</textString>
</resultScore>
</result>
</resultRecord>
</replaceResultRequest>
</imsx_POXBody>
</imsx_POXEnvelopeRequest>
XML;
?>
The XML output in browser after parsing (during cURL request):
<?xml version="1.0" encoding="UTF-8"?>
<imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
<imsx_POXHeader>
<imsx_POXRequestHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>53e4657ec1499</imsx_messageIdentifier>
</imsx_POXRequestHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
<replaceResultRequest>
<resultRecord>
<sourcedGUID>
<sourcedId>bbgc15659375gi290156</sourcedId>
</sourcedGUID>
<result>
<resultScore>
<language>en-us</language>
<textString>0.7</textString>
</resultScore>
</result>
</resultRecord>
</replaceResultRequest>
</imsx_POXBody>
</imsx_POXEnvelopeRequest>
Since there is so little detailed information on how to do this in LTI, I've posted my solution below. This is a duplicate of my addition to Blackboard's EduGarage forums, but to get it into the public domain I've put it here. I hope it helps other people trying to implement LTI tools.
Here is how to pass back a grade using PHP cURL, the contents of the envelope.php file shouldfollow the XML found in the IMS Global Documentation found here. The cURL request constructs the header and then adds the XML body below it.
Note that the envelope.php file contains the $xml variable in the following format (you will obviously need to add your own $id and set a grade with a variable etc...):
PHP code for passing grade using cURL:
include("xml/envelope.php");
$xml_length = strlen($xml);
$url = $this->lis_outcome_service_url;
$bodyHash = base64_encode(sha1($xml, TRUE)); // build oauth_body_hash
$consumer = new OAuthConsumer($key, $secret);
$request = OAuthRequest::from_consumer_and_token($consumer, '', 'POST', $url, array('oauth_body_hash' => $bodyHash) );
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, '');
$header .= $request->to_header(); // add content type header
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("POST http://your-tools-url-here.edu.au HTTP/1.0",
"Content-Length: $xml_length", $header, "Content-Type: application/xml"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

Print as XML file when using cURL

How can I display the data returned from cURL as an XML document on the page?
Currently I get something like this:
[something] => 189129
[somethingElse] => exampleContent
[somethingElse1] => someMoreExamples
[somethingElse2] => evenMoreExamples
From this code:
$url = "http://example/";
$header[] = 'Accept: application/xml';
$header[] = 'Accept-Encoding: gzip';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$xmlResponse = new SimpleXMLElement($response);
?>
<?php
print_r('<pre>');
print_r($xmlResponse);
print_r('</pre>');
?>
Is there a way to format the response directly as XML or a way to transform it after with php?
Thanks.
Edit:
If the data you are fetching is already xml, all you need to do is
echo htmlentities($xmlResponse);
Previous answer (for posterity):
I believe you can do something like:
// start your xml with a simple doctype
$xml = new SimpleXMLElement('<?xml version="1.0" standalone="yes"?><data/>');
// loop through each array entry, adding the key/value as a child to 'data'
foreach($response AS $key=>$value)
{
$xml->addChild($key, $value);
}
// get the xml
$xmlResponse = $xml->asXML();
// output it, encoding the html characters so it displays ok
echo '<pre>';
echo htmlentities($xmlResponse);
echo '</pre>';

How to traverse xml in php

I am using the following function
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$myTestingUrl = file_get_contents_curl("myUrl");
After I run that function I have
$myTestingUrl =
<?xml version="1.0" encoding="UTF-8"?>
<map>
<entry key="keyName">
<entry key="ActionUrl">http://www.my_actionUrl.com/</entry>
</entry>
</map>
Can you please tell me how can I traverse $myTestingUrl to get the content of entry key "ActionUrl" (http://www.my_actionUrl.com/) in a variable in php?
Thank you!
Try
$xml = simplexml_load_string($myTestingUrl );
$items = $xml->xpath('/map/entry/entry[#key="ActionUrl"]/text()');
echo $items[0];
I prefer #air4x's XPath method but here it is without XPath - for the purpose of showing element and attribute access in SimpleXML:
Codepad demo
$obj = simplexml_load_string($myTestingUrl);
foreach($obj->entry as $entry)
{
if(isset($entry->entry))
{
foreach($entry->entry->attributes() as $key => $value)
{
if($key == 'key' && $value == 'ActionUrl')
{
echo 'ActionUrl is: ' . (string)$entry->entry;
break 1;
}
}
}
}

Categories