try use data from json file with php - php

I am trying to get my data from a json file with php
<?php
$url = 'path/to/my/file.json';
$data = file_get_contents($url);
$characters = json_decode($data);
echo $characters[0]->name;
?>
I got the message
Notice: Trying to get property of non-object
when I do the echo.
Somebody can help me with this?
file.json
[
{
"name": "Aragorn",
"race": "Human"
},
{
"name": "Legolas",
"race": "Elf"
},
{
"name": "Gimli",
"race": "Dwarf"
}
]

Related

How to put an API return string into an array

I have a string that i get from an API and i wish i could put it in a array so i could check the values that came from the return.
String return example:
{
"code":"000",
"message":"XXX",
"date":"2018-05-17",
"hour":"09:16:09",
"revision":"",
"server":"XX",
"content":{
"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
}
}
What I need:
echo $string['code'];
Javascript has no problem with JSON encode command. But how can I do it with PHP?
First of all your JSON data seems to be invalid (Some brackets missing). It needs to be like this:-
{
"code": "000",
"message": "XXX",
"date": "2018-05-17",
"hour": "09:16:09",
"revision": "",
"server": "XX",
"content": {
"nome": {
"info": "SIM",
"conteudo": [{
"field1": "XXXX",
"field2": "XX"
}]
}
}
}
Now You need to decode this JSON data and then get data based on the index
$array = json_decode($json,true);
echo $array['code'];
Output:-https://eval.in/1005949
You can decode the JSON string to Array in PHP.
$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);
var_dump($decodedValue);
Your example string is not valid json, you are missing some closing brackets.
This should be the correct way:
'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'
As for your question. in PHP you can easily use json_decode
Example:
<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';
$decoded_json = json_decode($json, true);
echo $decoded_json['code'];
You can see it working here

decode json file with php

I am trying to decode a json file with php, but it's not displaying anything. The code I have so far:
PHP
$str = file_get_contents('llt_stops.json');
$json = json_decode($str, true);
print_r($json, true);
JSON
{
"stops": [
{
"id": "1",
"name": "Andreaskyrkan",
"locId": "740037195"
},
{
"id": "2",
"name": "Ankarkronan",
"locId": "740037329"
},
{
"id": "3",
"name": "Arcushallen",
"locId": "740037262"
}
]
}
I've also tried with a foreach loop, but it doesn't display anything either.
foreach ($json['stops'] as $field => $value) {
// Use $field and $value here
}
Update:
I get this error, don't know whats wrong with the loop:
Invalid argument supplied for foreach()
Use
print_r($json);
With true it returns the value, does not print it.
It works now. It was the swedish characters in the json file that were not correctly displayed. I changed them from ? to å ä ö, and it worked.

JSON-LD to PHP array

How do I convert JSON-LD extracted from website to a PHP array.
This is the Error I'm getting with the following code---
"Warning: Illegal string offset 'name' in
/Users/lightingsystem/sigclub/signatureclub/public/json/json2php.php
on line 12 {"
--code--
$json = '{ "#context": "http://schema.org", "#type": "LodgingBusiness", "name":"Breakerwood Suites", "amenityFeature":"A nice place to sleep", "audience":{ "#type":"Audience", "audienceType":"All" }, "checkinTime":"16:00", "checkoutTime":"10:00", "petsAllowed":"No", "availableLanguage":"", "openingHours":"", "paymentAccepted":"", "address":"2323 Bowers St.,New Orleans,LA,USA,69969", "image": "https://www.picturebook.com/resort2.jpg", "telephone":"Resort telephone number: 504/339-4543" }';
$coded = json_encode($json);
$data = json_decode($coded, true);
echo $data['name'];
Your call to json_encode is wrong because $json is already in the JSON format.
So what happens is: your JSON gets converted to JSON again, returning a JSON string.
Remove the json_encode call and your code works as expected.
<?php
$json = '{ "#context": "http://schema.org", "#type": "LodgingBusiness", "name":"Breakerwood Suites", "amenityFeature":"A nice place to sleep", "audience":{ "#type":"Audience", "audienceType":"All" }, "checkinTime":"16:00", "checkoutTime":"10:00", "petsAllowed":"No", "availableLanguage":"", "openingHours":"", "paymentAccepted":"", "address":"2323 Bowers St.,New Orleans,LA,USA,69969", "image": "https://www.picturebook.com/resort2.jpg", "telephone":"Resort telephone number: 504/339-4543" }';
$data = json_decode($json, true);
echo $data['name'];
Note:
You can get the last JSON error with json_last_error_msg

Save json data from input into database

I get the json data using cURL as an input:
curl -H "Content-Type: application/json" -X GET http://localhost:8000/jsontest --data-binary #test.json
It is simple json with couple of fields:
{
"id": "12345",
"blockId": "9000",
"spot": {
"id": "7890",
"length": 23,
"name": "test",
"country": "de"
},
"channel": "tv:rtl.de",
"startTimestamp": "1323872435345",
"endTimestamp": "13243498394384329"
}
And this is my code for getting the data and storing in database:
public function test()
{
$string = file_get_contents('php://input');
$json_a = json_decode($string, true);
foreach ($json_a as $json => $test) {
$tvib = new TVIB;
$tvib->spotid = $test["spot"]["id"];
$tvib->name = $test["spot"]["name"];
$tvib->channel = $test["channel"];
$tvib->start = $test["startTimestamp"];
$tvib->end = $test["endTimestamp"];
$tvib->save();
}
var_dump($json_a);
}
When I run cURL request I get this error and a lot of html and js code:
ErrorException: Illegal string offset 'spot' in file TestController.php on line 18 ($tvib->spotid = $test["spot"]["id"];)
If I run this locally like this:
$string = file_get_contents('test.json');
everything works fine. But there is obviously problem with php input.
Any suggestions?
PS I use Laravel 5.5
not need foreach. so change code to :
public function test()
{
$string = file_get_contents('php://input');
$json_a = json_decode($string, true);
//foreach ($json_a as $json => $test) {
$tvib = new TVIB;
$tvib->spotid = $json_a["spot"]["id"];
$tvib->name = $json_a["spot"]["name"];
$tvib->channel = $json_a["channel"];
$tvib->start = $json_a["startTimestamp"];
$tvib->end = $json_a["endTimestamp"];
$tvib->save();
//}
var_dump($json_a);
}

json_decode doesn't work on my string

I have JSON Object which I have encoded like so
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);
I am taking this JSON data and storing it in a file like so
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
which looks something like this in the file
var tour =
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
Now I am reading it back form the second line like so
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,
$lines = file_get_contents("path",NULL,NULL,10);
$a = json_decode($lines);
Now according to expected output the $a should have the decoded data but it has null.
Can someone point out the mistake?
I believe the issue is the semicolon at the end of the JSON you've read back in from the file. Try chopping that off before attempting json_decode:
$a = json_decode(rtrim($lines, ";"));
pass the second parameter true for recursively decoding
$a = json_decode(chop($lines,";"),true);
check the php mannual here json_decode
It will be
$str = file_get_contents('http://example.com/example.json/');
$json = json_decode($str, true); // decode the JSON into an associative array
See the post
Parsing JSON file with PHP
try to save data in file like
$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);
instead of
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
//and read like
// Read JSON file
$json = file_get_contents('path');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);

Categories