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);
Related
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.
I am using PHP with cURL to make requests to an API.
The API responds with an encrypted string which I then have to use json_decode on and run it through a pre-defined decrypt method that returns a string.
So I have something like this:
echo $response;
$decodedResponse = json_decode($response, true);
// New instance of Decrypt
$decrypt = new Decrypt();
$decryptedResponse = $decrypt->decrypt($decodedResponse);
echo $decryptedResponse;
Using var_dump($decryptedResponse) yields string(960) but the string looks like a JSON array.
{"Title":"Mr","Forenames":"Steve"}
So what is the best way to rip apart this string so that I can use the variables through an associative array?
I had already tried:
foreach(decryptedResponse as $data)
{
echo $data['Title'];
}
But this outputted nothing on the screen.
Am I misinterpreting the use of json_decode?
As many have stated it seems you have to decode twice, I'll look into this and share my findings.
You need to json_decode again on the decrypt result
$decodedResponse = json_decode($response, true);
// New instance of Decrypt
$decrypt = new Decrypt();
$decryptedResponse = $decrypt->decrypt($decodedResponse);
$decryptedArry = json_decode($decryptedResponse, true);
var_dump($decryptedArry);
echo $decryptedArry['Title'];
As you told Using `var_dump($decryptedResponse)` yields string(960) but the string looks like a JSON means your decrypt duration convert it again json. You can try bellow code it may resolve your issue
$decodedResponse = json_decode($response, true);
// New instance of Decrypt
$decrypt = new Decrypt();
$decryptedResponse = $decrypt->decrypt($decodedResponse);
$decryptedResponse = json_decode($response, true);
foreach(decryptedResponse as $data)
{
echo $data['Title'];
}
The code below shows that the json_decode works like you want it to but it seems like your Decryption class does something weird.
$response = '{"Title":"Mr","Forenames":"Steve"}';
$decodedResponse = json_decode($response, true);
var_dump($decodedResponse);
echo $decodedResponse["Title"];
May be I am missing something very basic here, but this is what I tried and in some cases my JSON is not a valid JSON.
Code -
$hash_tag = $_POST['hash_tag'];
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = "?q=#".$hash_tag."&count=30";
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$data = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$tdata = json_decode($data);
$newArr0 = array();
foreach($tdata as $k=>$v) {
if($k == "statuses")
$newArr0 = $v;
}
foreach ($newArr0 as &$nval1) {
unset($nval1->source);
if(isset($nval1->retweeted_status)) {
unset($nval1->retweeted_status);
}
}
//stripslashes($newArr0);
$myarray = array('response'=>'1','message'=>'Tweet result', 'tweet_data'=>$newArr0);
echo json_encode($myarray);
Like I searched for Britney but it gives me an Invalid JSON - JSON
Error -
Parse error on line 623:
... "location": "WVU 2017 \u
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
But If I search "sachin" I am getting Valid JSON, Let me know what I am doing wrong here, as I need to send the JSON encoded stream to mobile devices from back end.
The JSON response contains no errors. The error is that you are pasting the response into http://jsonlint.com/ or some other service which clearly cuts the string at exactly the offset you are showing the error.
Stop using the service for such long string and remember to check what you pasted to the original response you got in PHP.
Also, when you have problems like this, cut your logic into smaller parts. Such as
$tdata = json_decode($data);
after this do a
var_dump($tdata);
die;
as you want to cut out whatever you are doing after getting and decoding the response and narrowing the reason to the failure. The rest of the code is when debugging the response, just noise.
If you only run the code in top, and not manually copy pasting it, it works fine..
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 am attempting to write PHP code to interact with JSON output from Mapquest's Open API / Open Street Map service. I have listed it below. I have been using this code in my Drupal 6 implementation. This code returns no output. When I use it, json_last_error() outputs 0.
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode(var_export($json));
$foo .= $obj->{'fuelUsed'};
$output .= foo;
return $output;
}
You can view the raw JSON output by following the URL. In this function I am expecting to get 1.257899 as my output. I have two questions:
(1) What can I call so I get items out of my array. For instance, how can I get the value represented in JSON "distance":26.923 out of the array?
(2) Is it possible am I running into a recursion limit issue that I've read about in the PHP Manual?
If you read the manual page for json_decode carefully, you'll notice there is a parameter (false by default) that you can pass to have it return an array rather than an object.
$obj = json_decode($json, true);
So:
<?php
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json, true);
//var_dump($obj);
echo $obj['route']['fuelUsed'];
}
json_test_page();
Remove the var_export function from json_decode.
You're trying to convert information about a string to json.
I was able to get the fuelUsed property this way
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json);
return $obj->route->fuelUsed;
}