How can I read a JSON data response using php?
This is Code :
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
and give me this json data :
{
"original": "This sentnce has some probblems.",
"suggestion": "This sentence has some problems.",
and ...
}
I want to return "suggestion" in a url with $
this is an example :
$user_id = '123456789'
$mytext = '?' // I WANT RETURN "suggestion" HERE !
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
You can use json_decode().
See:
http://php.net/manual/en/function.json-decode.php
You just need to do:
$response = json_decode($response,1);
echo $response['suggestion'];
Setting the second parameter of json_decode() to 1 (true) will return an associative array of the JSON data.
If you want to include it in a URL using your code example:
$user_id = '123456789'
$json = json_decode($response,1);
$mytext = $json['suggestion'];
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
Use json_decode to convert json_response to array.Add second parameter of 'true' to make it an array that you should be familiar with.
Access suggestion variable by specifying it.
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
$data=json_decode($response,true);
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion'];
echo $url;
Related
I am getting this string from CURL response
{status: 'false',description:'5400'}
I want to extract description parameter only.
I want $description = 5400 ;
How to do this ?
You have a bad json response, you have to change your json code and than using the following code you can access the variable.
<?php
$response = '{"status":false,"description":5400}';
$response_array = json_decode($response);
echo $response_array->description;
?>
And if you want to get the value of description with the existing bad json, you can do following thing.
<?php
$response = "{status:'false',description:'5400'}";
$r = explode("description:'", $response);
$description = rtrim($r[1],"'}");
echo $description;
?>
That response is json. Turn it into a PHP array:
$response = "{status: 'false',description:'5400'}";
$response_array = json_decode($response, true);
$description = $response_array['description'];
echo $description;
# Nirali Joshi
If Your JSON with space then it will be write solution
$response = "{status : 'false', description : '5400'}";
$response = str_replace(" ","",$response);
OR
$response = preg_replace('/\s+/', '', $response);
$t_repsonse = explode("description:", $response);
$i_description = str_replace("}","",str_replace("'","",$t_repsonse [ 1 ] ));
OR
$i_description = str_replace("}","",preg_replace('([ "\' ])', '', $t_repsonse [ 1 ]));
$description = $i_description;
Sorry and improve if any mistake founds and thanks
I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
I have probably spent all day trying to figure this out. I have read multiple questions here on stack and also have been reading articles and checking on documentation, but I can't seem to figure out why this batch of code just produces a null output. Am I missing brackets, calling something wrong, ect?
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
refresh_requency => 30
);
echo json_encode($array);
?>
Again what I'm asking is can someone point out to me or tell me what I'm doing wrong. Is it my server that's just not handling the data correctly? That could be a possibility.
One other thing I've tried is to just print out $temp and/or the other variable like $str. When I do that though they don't even show up so that's what I think my problem is just not sure how to fix it.
Update
I've come to the conclusion that it's my web hosting service. As if I add var_dump($json) I get a null output null output.
Also to confirm that its my webhost if I run error_reporting(E_ALL); ini_set('display_errors', 1); it points to the file php.ini not allowing outgoing connections. I edited that same file on my local home server(raspberry pi) ran the same file and it works fine.
Below is the working solution for your above code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
When I executed your code, I found 2 problem into your code snippet:
1) You were trying to use object of type stdClass as array.
Solution:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json->main->temp_min;
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
2) You did not put array key into quotes:
$array = array(
"content" => $content,
refresh_requency => 30
);
It should be :
$array = array(
"content" => $content,
"refresh_requency" => 30
);
Access $temp like this
$temp = $json->main->temp_min;
you will get the desired output.
Also, you need to allow allow_url_fopen in your php.ini config file. Some hosts disallow it for security reasons
$json = json_decode($str, true);
You need second argument to convert json string into associative array instead of the object. And you are trying to use array ($json['main']['temp_min']), not object. Also
$array = array(
"content" => $content,
"refresh_requency" => 30
);
The code looks like
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$content = $json['main']['temp_min'];
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
And result is http://codepad.viper-7.com/euBNAk :
{"content":44.6,"refresh_requency":30}
The second parameter of json_decode() is assoc (associative). By default it is 0. When it is 0 (default) the json_decode() will return an object, not an array. That's why you are unable to access temp_min by using $json['main']['temp_min'];
However If you use with the value 1 as second parameter, the function will return an array. Parameter 1 means setting associative to 1 (true). So use $json = json_decode($str, true); instead of $json = json_decode($str);. You will be able to access with $json['main']['temp_min']; now.
Also you forgot double quote on line 13 (refresh_requency). Goodluck.
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
Just want help
I change your code like this and that be correctly
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, TRUE); // Wrong here
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30 // And wrong here, it's must string
);
echo json_encode($array);
?>
More information about json decode in php to array or object http://php.net/manual/en/function.json-decode.php
I'm using the following to pull some data fro facebook:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
echo $tagData;
This produces e.g.:
{"data":
[
{"name":"Jonathan Montiel","id":"28125695"},
{"name":"Jackson C. Gomes","id":"51300292"}
],
"paging":{"next":"https:\/\/graph.facebook.com\/123456789\/friends?access_token=5148835fe&limit=5000&offset=5000&__after_id=100060104"}}
QUESTION How I can just return ONLY what's inside the [...] including the [ ]?
Desired result:
[
{"name":"Jonathan James","id":"28125695"},
{"name":"Jackson C. Cliveden","id":"51300292"}
]
Try this:
$tagData = json_decode( $tagData, true );
$data = $tagData['data'];
echo json_encode( $data );
This basically converts the JSON to an array, extracts the desired part and returns this again as JSON-encoded.
EDIT
Example Fiddle
json_decode and reencode with json_encode necessary part of the response. Following is going to work for you:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
$tagData = json_decode($tagData);
echo json_encode($tagData->data);
Thanks to Sirco for the inspiration, this works although how its different to answer given I have no clue!
$tagData = json_decode(file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token), true );
$data = $tagData['data'];
echo json_encode( $data );
My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result, it shows "$result", instead of showing Hello.
How can I solve this?
The basic problem with your example is that $result is wrapped in single-quotes. So the first solution is to unwrap it, eg:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
But this is still not "good enough", as it is always possible that $result could contain a " character itself, resulting in, for example, {"result":""","count":3}, which is still invalid json. The solution is to escape the $result before it is inserted into the json.
This is actually very straightforward, using the json_encode() function:
$result = 'Hello';
echo '{
"result":'.json_encode($result).',
"count":3
}';
or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just $result:
$result = 'Hello';
echo json_encode(array(
'result' => $result,
'count' => 3
));
You should use json_encode to encode the data properly:
$data = array(
"result" => $result,
"count" => 3
);
echo json_encode($data);
You're using single quotes in your echo, therefore no string interpolation is happening
use json_encode()
$arr = array(
"result" => $result,
"count" => 3
);
echo json_encode($arr);
As a bonus, json_encode will properly encode your response!
Try:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
$result = 'Hello';
$json_array=array(
"result"=>$result,
"count"=>3
)
echo json_encode($json_array);
That's all.