So im using the spaceX api to try and understand retrieving data using php a bit more,
my base url is : https://api.spacexdata.com/v5/launches/
from here it returns:
from here i want the webcast link, but i cannot acces it somehow.
my current code:
$api_url = 'https://api.spacexdata.com/v5/launches/';
$json_data = file_get_contents($api_url);
$data = json_decode($json_data, true);
//var_dump($data);
$i = 0;
foreach ( $data as $launches)
{
$i++;
if($i > 2) break;
var_dump($launches["fairings"],
$launches["links"], '<br/>');
}
that returns:
how can i return the 'webcast' url
$launches["links"]["webcast"]
You can chain your properties to go down the objects/arrays values... This is the same as doing
$links = $launches["links"];
$links["webcast"];
Related
I have Json Data with multiple array, and i try to get the data inside effect_property, but it keep return nothing.
Here is my code
$json = file_get_contents('data.json');
$json_data = json_decode($json,true);
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i][effect_property];
}
when i print the $path_data_action it show something like this:
{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
How can i get the source_path?
Probably the JSON you are decoding with :
$json_data = json_decode($json,true);
contains another JSON string at key effect_property. You could change that to JSON Object and it should work fine.
Otherwise, you could use json_decode again, like :
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i]effect_property];
$pathDataActionArr = json_decode($path_data_action , true);
$sourcePath = $pathDataActionArr['propTo']['sourcePath'];
}
Furthermore, to know any last occurred error with JSON encoding/decoding
json_last_error — Returns the last error occurred
UPDATE : I tried to decode the JSON you posted with code :
$fileContent = file_get_contents("/home/tarun/Desktop/test/abcd");
$jsonArray = json_decode($fileContent,true);
var_dump($jsonArray['t03_action']['data'][9]['effect_property']);
$effectPropertyArr = json_decode($jsonArray['t03_action']['data'][9]['effect_property'],true);
if(isset($effectPropertyArr['propTo']['source_path'])) {
var_dump($effectPropertyArr['propTo']['source_path']);
} else {
var_dump("No such key!");
}
Here, not all your elements of the array at key effect_property contains source_path. That's why :
if(isset($effectPropertyArr['propTo']['source_path'])) {
The above is working fine, with output :
/home/tarun/Desktop/test/temp.php:6:
string(205) "{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/18032022375907620062/","source_file":"1804100413270066.jpg","source_name":"Penguins.jpg"},"beforeAction":"0","action_order":"1"}"
/home/tarun/Desktop/test/temp.php:10:
string(32) "../uploads/18032022375907620062/"
// decoded array passed key of that array
$json_data['propTo']['source_path'];
try this ,Its working for me.
var data = {"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
alert(data.duration);
var Prop = data.propTo;
alert(Prop.source_path);`enter code here`
In addition to the question yesterday: Question
I got multiple (3) Items in the json file:
results.json
["{\"Produkt\":{\"Produktkategorie\":\"Artikel1\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante1\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel2\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante2\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel3\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante3\"}}}"]
I want echo all three value from "Produktkategorie" and the value "MaxBreite"
It should look like this:
Artikel1 - 250
Artikel2 - 250
Artikel3 - 250
My code looks like this:
$json = file_get_contents('results.json');
$json = json_decode($json, true);
$anzahl = count($json) -1;
$anzahlstart = 0;
while ($anzahlstart < $anzahl) {
$json = json_decode($json[$anzahlstart], true);
$ProduktkategorieFile = $json['Produkt']['Produktkategorie'];
$MaxBreiteFile = $json['Produkt']['Optionen']['MaxBreite'];
echo $ProduktkategorieFile. "-" .$MaxBreiteFile;
$anzahlstart ++;
}
Unfortunately my Code throws a error after passing first line:
Notice: Undefined offset: 1 in
After that I don't get any result.
Kings of coding, could you help me again please :)
Do you need like this?:-
<?php
$json_string = file_get_contents('results.json');
$json = json_decode($json_string, true);
// I hope the above line gives you exact json what you shown to us
foreach ($json as $jso){
$array = json_decode($jso, true);
echo $array['Produkt']['Produktkategorie'].' - '.$array['Produkt']['Optionen']['MaxBreite'];
echo PHP_EOL;
}
Output:-https://eval.in/728430
Note:- If yes then I hope you are able to get other values easily.Thanks
The problem is with the $json variable name: You're reassigning it on this line: $json = json_decode($json[$anzahlstart], true);
Rename this variable and you're good to go!
I would also replace the while loop with a foreach loop as shown in my example:
<?php
//With foreach
$original = '["{\"Produkt\":{\"Produktkategorie\":\"Artikel1\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante1\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel2\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante2\"}}}","{\"Produkt\":{\"Produktkategorie\":\"Artikel3\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Kante3\"}}}"]';
$decoded = json_decode($original);
foreach($decoded as $encodedProduct){
$product = json_decode($encodedProduct,true)['Produkt'];
echo $product['Produktkategorie'] . " - " . $product['Optionen']['MaxBreite'] . "\n";
}
//Original fixed code
$json = json_decode($original, true);
$anzahl = count($json);
$anzahlstart = 0;
while ($anzahlstart < $anzahl) {
$decodedJson = json_decode($json[$anzahlstart], true);
$ProduktkategorieFile = $decodedJson['Produkt']['Produktkategorie'];
$MaxBreiteFile = $decodedJson['Produkt']['Optionen']['MaxBreite'];
echo $ProduktkategorieFile. " - " .$MaxBreiteFile . "\n";
$anzahlstart ++;
}
Your problem is, that you are trying to decode an array of json string, instead of the string itself.
so that would be like this now.
$json = file_get_contents('results.json');
$json = json_decode($json[0], true); // notice [0];on this line.
...
After reading the other question, I have had this problem before, but you essentially need to do two things. in your ajax.
$.ajax({
...
data : JSON.stringify(data)
})
This changes an object into a json string,
Then on your server you do the decode.
something like this
$json = json_decode($jsonstringGoesHERE , true);
For more information in understanding the issue, have a look at this other post.
jQuery ajax, how to send JSON instead of QueryString
I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]
I try to put a JSON Object into a PHP Variable, it is not working. When I var_dump it, it says NULL.
PHP:
<?php
$json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/drantifat'));
$data = json_decode($json, false);
$money = $data->tplc->stats; // -> What do i have to do to reach the id:GTA Online Cash and use the val: $33.9K ?
?>
JSON file example: (it changes over time)
{"cid":0,"ttl":"Grand Theft Auto V",
"ishs":false,"issa":false,"istc":false,"htl":true,"tlc":"text",
"tlt":"View Stats","tlh":"/member/drantifat/games/gtav/career/overview",
"iso":false,"cmng":false,"order":0,"uid":0,"ttc":0,
"tplc":"{\"game\":\"GTAV\",\"stats\":[{\"id\":\"Game Progress\",\"val\":\"58.77%\"},
{\"id\":\"Missions Passed\",\"val\":\"55\"},{\"id\":\"Playing Time\",\"val\":\"29:00:33\"},
{\"id\":\"GTA Online RP\",\"val\":\"2.4M\"},{\"id\":\"GTA Online Rank\",\"val\":\"128\"},
{\"id\":\"GTA Online Cash\",\"val\":\"$33.9K\"},
{\"id\":\"GTA Online Playing Time\",\"val\":\"529:44:12\"}],
\"url\":\"/member/drantifat/games/gtav/career/overview\"}","isa":false,"cnt":""}
Could anyone also help me with what I've mentioned in the PHP file?
tplc isn't a JSON object, it's a string that is itself JSON.
<?php
$json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/drantifat'));
$data = json_decode($json, false);
$tplc = json_decode($data->tplc);
$money = $tplc->stats;
?>
To get the money value specifically:
<?php
$json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/drantifat'));
$data = json_decode($json, false);
$tplc = json_decode($data->tplc);
$stats = $tplc->stats;
foreach ($tplc->stats as $stat) {
if ($stat->id == 'GTA Online Cash') {
$money = $stat->val;
break;
}
}
echo $money;
?>
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);