How to add attribute in JSON in PHP? - php

I have Json in PHP like this:
$json = '{"total":"100", "page":"1", "records":"100", "rows": [
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';
and I want to add
"test1":"5","test2":"7"
into JSON above.
so it will be like this:
$json = '{"total":"100", "page":"1", "records":"100", "rows": [
{"no":"1","part_number":"2","part_name":"3","price":"4","test1":"5","test2":"7","note":"8"}]}';
Please, help me. How to add attribute in JSON in PHP?

$json = '{"total":"100", "page":"1", "records":"100", "rows": [
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';
// decode json
$json = json_decode($json);
// add data
$json->rows[0]->test1 = "5";
$json->rows[0]->test2 = "7";
// echo it for testing puproses
print_r($json);
// re-encode
$json = json_encode($json);
echo $json;

Related

PHP: Unable to echo values from nested Array in 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;

PHP load json data, output is empty

I try to load data from my JSON file into php see my code below
JSON:
{
"drinks":[
"1" {"coffee": "zwart", "country":"afrika"},
"2" {"tea": "thee", "country":"china"},
"3" {"water": "water", "country":"netherlands"},
]
}
PHP:
<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0][coffee];
echo $drinks;
?>
If I run this code my output is empty. Who can help me in the right direction?
Your JSON input is NOT valid according to RFC 4627 (JSON specification). So the correct json string must be:
{"drinks":[
{"coffee": "zwart", "country":"afrika"},
{"tea": "thee", "country":"china"},
{"water": "water", "country":"netherlands"}
]
}
so your code would work:
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0]['coffee'];
echo $drinks;
Or at least, you must format your json string like below:
{
"drinks":[
{
"1": {"coffee": "zwart", "country":"afrika"},
"2": {"tea": "thee", "country":"china"},
"3": {"water": "water", "country":"netherlands"}
}
]
}
And you can get your data in this way:
$str = file_get_contents('data.json');
$json = json_decode($str, true);
$drinks = $json['drinks'][0]['1']['coffee'];
echo $drinks;

parse json with php 5 not working

I am trying to parse and list a json file. I have it as Unicode-8 without BOM. File is operational. Structure:
// "games.json" :
// {"data":[
// {"game":"5359","Date":"07/08/2015"},
// {"game":"5355","Date":"10/20/2007"},
....
<?php
// copy file content into a string var
$jsondata = file_get_contents("games.json");
// convert the string to a json object
$json = json_decode($jsondata,true);
var_dump($json); // DW!
foreach($json["data"] as $data_X)
{echo $data_X->game;}
?>
Why doesn't this work?
<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
use $json = json_decode($jsondata); instead of `$json = json_decode($jsondata,true); True parameter convert it into array not json object.

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'];

Categories