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
Related
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
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.
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"
}
]
After executing CURL I am getting the $result variable value as:
{
"ErrorCode": "000",
"ErrorMessage": "Success",
"JobId": "6878b812-766d-48a2-9dae-2b0edf2d84d4",
"MessageData": [{
"Number": "919730842844",
"MessageParts": [{
"MsgId": "919730842844-64a40d7611f94c03bea1045fdfa9bac5",
"PartId": 1,
"Text": "\u0027messagecontentsmstest\u0027"
}]
}]
}
Now i need to check for the ErrorCode == 000, so how can I get the value of individually ErrorCode?
This response received is like JSON.
So I thought to decode it as an json_decode:
$chk = json_decode($result);
echo $chk->ErrorCode;
or we can even try in another way like,
$array = json_decode($result, true);
echo $array['ErrorCode'];
I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.