I'm using Guzzle with Laravel to get an object from external API with a HTTP. The API return XML Object similar to this (https://www.w3schools.com/php/note.xml)
I need to check one value of the response body. Here is my code:
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
$stringBody = (string) $res->getBody()->getContents();
echo $stringBody;
which is working fine, I mean it display the body as below picture
but I couldn't get one value?
I tried different methods but non of them is working!
for example, this way:
$result = starts_with($stringBody, 'Tove');
or
splitName = explode(' ', $res->getBody());
$first_name = $splitName[0];
echo $first_name;
non is working? I think it consider the body text empty ?
I tried using json_decode but it doesn't work or not supported anymore.
Any idea?
Thanks
What you get from response is xml content. Due to browser compatibility with XML you see only text. You just need SimpleXML class of php for get content as per XML node. Here is sample code
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
$stringBody = (string) $res->getBody()->getContents();
$xml = simplexml_load_string($stringBody);
echo $xml->to;
Hope this help you.
Related
I have this simple statement to call a JSON response. It was working until recently I found out it stopped working. Not sure why its not working. Here is my code. Its very simple.
//Here is the response from the API
{"country":"US","state":"NY","city":"GLEN COVE"}
$zip = "11542";
$url = "http://ziptasticapi.com/".$zip;
$info = file_get_contents($url);
$info = json_decode($info);
$cityname = $info->city;
$statename = $info->state;
Not sure why its not picking up the data at the end. I even tried changing it to json_decode($info,true) and changing it to $info['city'].
I have a C# client, its send a json to my php server.
There is the json string:
{"data":[{"name":"1"}]}
Its a valid json. When i try it in PHP Sandbox its works good
$ad = '{"data":[{"name":"1"}]}';
$contents = utf8_encode($ad );
$results = json_decode($contents);
var_dump($results->data);
But,when i try in laravel 5.1, its not work good.
$response = $connection -> getData();
// return $response; (Its equal : {"data":[{"name":"1"}]} )
$contents = utf8_encode($response);
$results = json_decode($contents);
dd($results->data); // Error Trying to get property of non-object
I hope someone can help me.
Thanks!
Based on the comments, it looks like the socket_read() in the getData() method is reading 1 character at a time, and then concatenating each NUL terminated character into a response string. json_decoded() is choking on all the extra NUL characters.
You can either update your logic in the getData() method so it is not doing this, or you can run a str_replace on the results:
$response = $connection -> getData();
// get rid of the extra NULs
$response = str_replace(chr(0), '', $response);
$contents = utf8_encode($response);
$results = json_decode($contents);
dd($results->data);
I've got a really weird problem and I can't figure out why.
The situation is quite simple. My Android app uploads JSON data to a php script on my server. Right now I am trying to parse the data.
This is the JSON-Array passed to the script (via httpPost.setEntity ()):
[{"friends_with_accepted":"false","friends_with_synced":"false","friends_with_second_id":"5","friends_with_first_id":"6"}]
This is the php script:
<?php
// array for JSON response
$response = array();
$json = file_get_contents ('php://input');
$jsonArray = json_decode ($json, true);
foreach ($jsonArray as $jsonObject) {
$firstId = $jsonObject['friends_with_first_id'];
$accepted = $jsonObject ['friends_with_accepted'];
$secondId = $jsonObject ['friends_with_second_id'];
$synced = $jsonObject ['friends_with_synced'];
echo "accepted: ".$accepted."synced: ".$synced;
} ?>
And this is the response I get from the script:
accepted: synced: false
Why is the "synced" property correctly passed, but not the "accepted" property??
I can't see the difference. Btw, firstId and secondId are parsed correctly as well.
Okay, i just found the problem:
Instead of
$accepted = $jsonObject ['friends_with_accepted'];
I deleted the space between jsonObject and the bracket
$accepted = $jsonObject['friends_with_accepted'];
I have generated some XML which is saved to a file.
Dummy_Order.xml
In the following code I wanted to open the XML and use it in the method 'ImpOrders'
Here is my code
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$proxy = new SoapClient('http://soapclient/wsdl/Web?wsdl', array ('trace' => 1));
if (file_exists('Dummy_Order.xml')) {
$xml = file_get_contents('Dummy_Order.xml');
} else {
exit('Failed to open XML.');
}
$xmlstring = new SimpleXMLElement($xml);
$result = $proxy->ImportOrders($xmlstring);
var_dump($result);
echo "REQUEST:\n" . $proxy->__getLastRequest() . "\n";
?>
I am getting a response in $result of 0 imported 0 skipped. So i then did getLastRequest() and it's adding the code from the Method but not adding my XML. It wants my XML in a string - which it current is in and isnt moaning about that (It does moan if i use it ->asXML).
I have tried
$result = $proxy->ImportOrders();
and
$result = $proxy->ImportOrders($xmlstring);
And both show the same result in _getLastRequest, which led me to believe that my string isn't being plugged in.
When I check the functions using _getFunctions it provides the information of this...
ImportResult ImportOrders(string $Orders)
Any help would be awesome!
Ok so i resolved it. All i needed to do was wrap my answer in <<
Like below.
$teststring = <<<XML
$xml
XML;
$result = $proxy->ImportOrders($teststring);
Hope this helps out anyone else using PHP, SoapClient and XML.
I'm trying to parse the xml response from a soap service. However, I can't get simplexml_load_string to work! Here is my code:
//make soap call
objClient = new SoapClient('my-wsdl',
array('trace' => true,'exceptions' => 0, 'encoding' => 'UTF-8'));
$soapvar = new SoapVar('my-xml', XSD_ANYXML);
$objResponse = $objClient->__soapCall($operation, array($soapvar));
//process result
$str_xml = $objClient->__getLastResponse();
$rs_xml = simplexml_load_string($str_xml);
...$rs_xml always has just one element with name Envelope.
However, if I use *"print var_export($objClient->__getLastResponse(),true);"* to dump the result to my browser, then cut and paste it into my code as a string variable, it work fine! This is what I mean:
$str_xml = 'my cut and pasted xml';
$rs_xml = simplexml_load_string($str_xml);
So it seems the problem is somehow related to something $objClient->__getLastResponse() is doing to the string it creates... but I'm at a loss as to what the problem is or how to fix it.
Do the following:
$str_xml = $objClient->__getLastResponse();
$str_xml = strstr($str_xml, '<');
$rs_xml = simplexml_load_string($str_xml);
As it's a quick and easy hack to strip off stuff before the first opening element.