I'm working on an sentiment api which giving output in json format now i want to parse it in php
{ "status": "OK", "usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html", "url": "", "language": "english", "docSentiment": { "type": "neutral" } }
This is my output json format.
I want output just "type" = "neutral"
Try reading the manual on how to decode json.
This will give you the PHP version of the data:
$strJson = '{ "docSentiment": { "type": "neutral" } }';
$data = json_decode($strJson);
var_dump($data);
This answer could have easily been found on google...
You can use json_decode and then go to the relevant thing:
$json=<<<JSON
{ "status": "OK", "usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html", "url": "", "language": "english", "docSentiment": { "type": "neutral" } }
JSON;
$json = json_decode($json);
echo $json->docSentiment->type;
Output: neutral
use json_decode, This is the PHP version of the data decoded
You can use json_decode() to decode it into a PHP object or array.
Below I added an example of using either of the 2.
$json = '{
"status": "OK",
"usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html",
"url": "",
"language": "english",
"docSentiment": {
"type": "neutral"
}
}';
// Convert to associative array
// (remove the second parameter to make it an object instead)
$array = json_decode($json, true);
$object = json_decode($json);
// Output the docSentiment type
echo $array['docSentiment']['type']; // Output: 'neutral'
echo $object->docSentiment->type; // Output: 'neutral'