get data from JSON with php - php

I am trying to get data from a JSON page:
http://www.oref.org.il/WarningMessages/alerts.json
I am getting errors.
How do I get the "data" array from the JSON?
Here is an example of what I am doing:
$homepage = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($result);
$result = utf8_encode($result);
print_r($result);

json_encode returns an object (or an associative array if you give the second argument true). To get the data array, you need to use a property accessor:
$homepage = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($homepage);
$data = $result->data;
print_r($data);
If you need to encode the $data array in UTF8, use:
$data = array_map('utf8_encode', $result->data);
To get the title, use:
$title = utf8_encode($data->title);

You could do this:
$result = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($result);
print_r($result->data);

$result = file_get_contents ("http://www.oref.org.il/WarningMessages/alerts.json");
$result = iconv('UTF-16', 'UTF-8', $result);
$json = json_decode($result);
echo $json->id;
echo $json->title;

First of all, you are first json_decode($result); but $result has not been declared before this line.
Secondly, the logically order of your code is totally wrong:
$result = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = utf8_encode($result); // encode the data before decoding json
$result = json_decode($result, true); // specify true to get an associated array
print_r($result);

Test.json:
{
"John":{
"name":"Json"
},
"James":{
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
json.php:
$result= file_get_contents("test.json");
$get_data = json_decode($result, true);
echo $get_data['John']['name'].'<br/>';
echo $get_data['James']['age'];

Related

Retrieve videoId From JSON Using PHP

Link To JSON File: https://pastebin.com/gXcnNnUK
Code I've Tried So Far:
$json = json_decode($json, true);
foreach($json as $data){
echo $data['videoId'];
}
But it's not returning values. Is there any better approach to do it?
On line 3, did you mean to iterate over $arr instead of $json?
$json = file_get_contents('json.json');
$arr = json_decode($json, true);
foreach($arr['contents']['sectionListRenderer']['contents']['2']['itemSectionRenderer']['contents'] as $pero){
$video_id_list .= $pero['compactVideoRenderer']['videoId'].',';
}

Loop over Array in array

I've got this data: http://api.tvmaze.com/shows?page=0
What i am trying to achieve is looping over the data and echo each id. This is the code i used:
<?php
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
foreach( $response as $serie){
foreach( $serie as $info => $value){
echo $info->$value["id"];
}
}
I don't really know what i am doing wrong.. Do you guys have any idea?
Greetz,
Try below code for getting id and url. You have to use array because you are passing TRUE in json_decode().
<?php
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
foreach( $response as $serie)
{
echo $serie['id']."->".$serie['url']."<br>";
}
?>
Keep it simple to fetch ids you wanted,
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
echo "<pre>";
foreach ($response as $value) {
echo $value['id']."<br/>"; // you will get ids in here only
}

Just get first json property?

I'm trying to get the json property's from an url. But just the first property arrives.
$json = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=' . $item_name);
$obj = json_decode($json, true);
$result = count($obj);
echo $json;
Output is:
"{"success":true}"
instead of:
"{"success":true,"lowest_price":"0,96\u20ac","volume":"143","median_price":"0,89\u20ac"}"
What am i doing wrong?

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);

Add new lines to JSON

I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.
$statement = $sql->prepare("SELECT data_filename,
data_filetype,
data_uniqid,
data_description,
data_coordinates,
exif_taken,
exif_camera,
exif_camera_seo,
exif_resolution,
exif_sensitivity,
exif_exposure,
exif_aperture,
exif_focallength,
is_downloadable,
is_notaccurate,
allow_fullsize
FROM photos
WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
That code gives me
[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]
Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.
$newdata = array('test' => 'just testing');
$json[] = $newdata;
What have I done wrong here?
json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.
As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().
Example about usage of json_encode and json_decode:
$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"
// ...
$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"
Try this:
$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);
or if you definately need it after its encoded:
$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);

Categories