PHP: Unable to echo values from nested Array in PHP - php

I want to echo data which is in JSON format. I converted from JSON to PHP array using json_decode() but it is not getting echoed. Blow is my code:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->extract;
?>
I only needed extract data which contains information for that title.

If you run the request in the browser, you will see that the returned JSON does not contain a pageids property, but is of the form
{
"batchcomplete": "",
"query": {
"normalized": [
...
],
"pages": {
...
}
}
}
If all you want is to grap the extract from the first item, you could do:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$page = reset($data->query->pages);
$extract = $page ? $page->extract : null;

Related

Get JSON from URL by PHP

I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);

How to get values of a json array in php?

I have json like this:
{
"Products": [
{
"_id": 1
....
},
{
"_id": 2
....
}
]
}
And got this json :
$str = file_get_contents($_FILES["uploadFile"]["tmp_name"]);
// convert object => json
$json = json_encode($str);
// convert json => object
$decoded = json_decode($json,true);
Now i want to see all _id of Producs.
I use this echo $decoded[0]['_id']; but it shows nothing.
Any ideas?
$decoded = json_decode($json, true);
echo $decoded['products'][0]['_id'];
This decodes the json as an array that you can use just like any other array in PHP, if you have trouble accessing values, then simply do a print_r($decoded) and that should show you its structure
If you want to loop over all the ids, then simply do a foreach loop
foreach($decoded as $inner_array) {
foreach($inner_array as $products) {
echo $products['_id'];
}
}
Working demo
You should be aware of using quotes on your json string :)
keys and values .
You don't need to encode it. the string is already in json format
$str= '{"Products": [{"_id": "1"},{"_id": "2"}]}';
$decoded = json_decode($str,true);
echo $decoded['Products'][0]['_id'];

Error while trying to read posted json data in php

I have the following problem. When i am trying to read some json data that are posted from an html page, i'm facing with the following error "Trying to get property of non-object on line".
Jquery script to create the json
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
Jquery for posting to php
$.post("page.php",{jsonData: JSON.stringify(json),
customer: $("#cusID").val()},function(data){});
PHP file
$json = json_decode($_POST['jsonData']);
foreach($json as $value){
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
Thanks in advance.
Thereafter:
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
You have:
Object[data][0] = array('serialNumber' => ...);
Need:
$json = json_decode($_POST['jsonData'][0]);
or
$json = json_decode($_POST['jsonData']);
foreach($json as $row){
foreach($row as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
}
json_decode without second parameter returns result as php object. You have to pass true as second parameter. Also your data are in $json['data'], not $json:
$json = json_decode($_POST['jsonData'], true);
foreach($json['data'] as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}

android, php, parsing JSON in php file sent from android

i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.
$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);

How do I parse a specific json data response?

Been yanking my hair out the past few days.
I want to parse just a single piece of data from a string response using Get method.
My php code I'm working with:
<?
include "function.php";
$request_rest->setMethod("GET");
$result = $request_rest->execute();
$response_status = $result[0];
$json_response_data = $result[1];
if ($response_status == "200") {
echo $json_response_data;
} else {
echo $response_status ." - connection failure";
}
?>
The results I get:
{"data1":"value1",
"data2":"value2",
"data3":"value3",
"data4":"value4",
"data5":"value5"}
I only want to display "value3" for my output but instead I'm getting the full string response.
If you know the key of the data you want (the data3 part) you can json_decode the json_response_data:
if ($response_status == "200") {
$decoded = json_decode($json_response_data);
echo $decoded['data3'];
}
Decode the JSON data and access it like any other array:
$data = json_decode($json_response_data, TRUE);
echo $data['data3'];

Categories