I can decode JSON in PHP To array But some data that have in JSON disappear when decode to array.
This is my JSON file
[
{
"name": "Games1",
"price": "€ 25.53",
"platform": "<span class=\"platform battle-net\"></span>",
"region": "GLOBAL",
"url": "localhost"
},
{
"name": "Games2",
"price": "€ 24.99",
"platform": "<span class=\"platform xbox-live\"></span>",
"region": "GLOBAL",
"url": "localhost"
}
]
This is my php code
$data = file_get_contents("game.json");
for ($i = 0; $i <= 31; ++$i) {
$data = str_replace(chr($i), "", $data);
}
$data = str_replace(chr(127), "", $data);
if (0 === strpos(bin2hex($data), 'efbbbf')) {
$data = substr($data, 3);
}
$data = json_decode($data,true);
print_r($data);
My result from print_r($data);
Array ( [0] => Array ( [name] => Games1 [price] => € 25.53 [platform] => [region] => GLOBAL [url] => localhost )
[1] => Array ( [name] => Games2 [price] => € 24.99 [platform] => [region] => GLOBAL [url] => localhost ) )
My value in Platform is disappear. Can anyone know What is the problem?
Your JSON contains HTML tags, and these are being interpreted by the browser when it shows the result of print_r(). Use the browser's View Source command to see the raw output and you should see the spans.
You can also use htmlentities() to convert them to escaped characters, which will be shown as is by the browser.
$output = print_r($data, true);
echo "<pre>" . htmlentities($output, ENT_COMPAT) . "</pre>";
Using <pre> will maintain the formatting as well.
In order to keep HTML inside of JSON, you have to follow multiple rules:
Escape quotation marks
<span class=\"class-name\"><\/span>
Escape the forward slash in closing tags <\/span>
In self closing tags, leave a space between slash and closing bracket.
<img ... />
Make sure to encode special character entities like this:
€
Additionally, you can avoid duplicating your
<span> tags, and just store their class name like this: "platform": "battle-net", or "platform": "xbox-live",.
Related
I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to decode json string that looks like the one below with json_decode php function:
"{id:"1",fields:[{id:"1",value:"asdasd"},{id: "2",value:"asdasd"},{id:"3",value:"asdasd"}]}"
I have tried various options from this question. Like:
$foo = utf8_encode($json_string);
$data = json_decode($foo, true);
Or:
json_decode(str_replace ('\"','"', $json_string), true);
Even with:
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
But, everything I try I always get null.
Why is that?
First of all, your JSON is invalid. You should always first validate your JSON before asking with any JSON lint tool, which would tell you exactly where and what the error is.
Also, you should always check for errors when handling JSON in PHP. You can check out the json_last_error function's official documentation on how to properly perform the validation.
$json = 'your_json_string';
$array = json_decode($json, true);
if (json_last_error()) {
die('Invalid JSON provided!');
}
printf('<pre>Valid JSON output: %s</pre>', print_r($array, true));
Worth mentioning: since PHP 7.3 a JSON_THROW_ON_ERROR option was added so the code can be wrapped around with a try-catch block:
try {
$array = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
printf('Valid JSON output: %s', print_r($array, true));
} catch (\JsonException $exception) {
printf('Invalid JSON input: %s', print_r($exception, true));
}
Working example.
<?php
$data='{
"id": "1",
"fields": [{
"id": "1",
"value": "asdasd"
}, {
"id": "2",
"value": "asdasd"
}, {
"id": "3",
"value": "asdasd"
}]
}';
$dataNew=json_decode($data,true);
echo '<pre>';
print_r($dataNew);
Your json was not valid. The json-keys need to be inside double-quotes. After that json_decode will work fine.
Output is:
Array
(
[id] => 1
[fields] => Array
(
[0] => Array
(
[id] => 1
[value] => asdasd
)
[1] => Array
(
[id] => 2
[value] => asdasd
)
[2] => Array
(
[id] => 3
[value] => asdasd
)
)
)
Your JSON returns Null because in JSON, the keys should be string.Your JSON format is incorrect and hence returns Null.
Try rewriting it as:
{
"id":"1",
"fields":[
{
"id":"1",
"value":"asdasd"
},
{
"id": "2",
"value":"asdasd"
},{
"id":"3",
"value":"asdasd"
}
]
}
Hi i have a JSON string like this:
{
"vidID": "CevxZvSJLk8",
"vidTitle": "Katy Perry - Roar (Official)",
"vidInfo": {
"0": {
"rSize": "67.79 MB",
"quality": "720",
"directurl": "https://r2---sn-5uh5o-f5f6.googlevideo.com/videoplayback?ipbits=0&mm=31&mn=sn-5uh5o-f5f6&itag=22&mt=1492837642&dur=269.165&id=o-AB1T_kZWIIiA_ihhSlAK4RXegp3Z9A18zn39hF0Aa51G&initcwndbps=197500&pl=21&source=youtube&mv=m&ip=137.74.1.176&mime=video%2Fmp4&ms=au&ratebypass=yes&requiressl=yes&sparams=dur%2Cei%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&key=yt6&lmt=1478841669593636&upn=Wp652d9rFKo&ei=OuX6WLqMDJaLNK-MmLAE&expire=1492859290&signature=A8B328D48101C553D0659D2D9D1F1B2F249D2035.792897E2CF6BFEFC97C81A90EA9CBF9B76FD0283&type=video%252Fmp4%253B%2Bcodecs%253D%2522avc1.64001F%252C%2Bmp4a.40.2%2522&quality=hd720&title=Katy%2BPerry%2B-%2BRoar%2B%2528Official%2529",
"dloadUrl": "//downloadmp.org/#download/22-58fae53acfc14-mp4-71087585/videos/CevxZvSJLk8/Katy%2BPerry%2B-%2BRoar%2B%2528Official%2529.mp4",
"ftype": "mp4",
"framerate": "",
"bitrate": "",
"codec": "",
"itag": "22",
"vidid": "CevxZvSJLk8"
}}}
And i am trying to get value of direct url.
So here is my PHP code:
$obj = json_decode($json);
echo $obj->vidInfo[0]->directurl;
Also tried this
echo $obj->vidInfo->0->directurl;
but i can't get the value of attribute direct url.
The problem is, "0" isn't a number, so you cant use the normal array access. Instead, you have to access it like an name. But as 0 isn't a valid identifier, you have to use the {}-syntax.
echo $obj->vidInfo->{"0"}->directurl;
The other way to get around this problem would be to pass true as second param to json_decode. Doing this would return you an assoc array and not the object format.
$data = json_decode($json, true);
echo $data['vidInfo'][0]['directurl'];
To get the object form try this:
var_dump(get_object_vars($obj));
I like to convert json to an array.
$array = json_decode($json,true);
echo $array ['vidInfo'][0]['directurl']
Here the rest of the data:
vidID => string: $array['vidID'] => CevxZvSJLk8
vidTitle => string: $array['vidTitle'] => Katy Perry - Roar (Official)
rSize => string: $array['vidInfo'][0]['rSize'] => 67.79 MB
quality => string: $array['vidInfo'][0]['quality'] => 720
directurl => string: $array['vidInfo'][0]['directurl'] => https://r2---sn-5uh5o-f5f6.googlevideo.com/vide truncated 687 char
dloadUrl => string: $array['vidInfo'][0]['dloadUrl'] => //downloadmp.org/#download/22-58fae53acfc14-mp4 truncated 60 char
ftype => string: $array['vidInfo'][0]['ftype'] => mp4
framerate => string: $array['vidInfo'][0]['framerate'] =>
bitrate => string: $array['vidInfo'][0]['bitrate'] =>
codec => string: $array['vidInfo'][0]['codec'] =>
itag => string: $array['vidInfo'][0]['itag'] => 22
vidid => string: $array['vidInfo'][0]['vidid'] => CevxZvSJLk8
I'm trying to decode some basic JSON data from Mintpal.com (https://www.mintpal.com/api)
The raw data looks like:
[
{
"market_id": "152",
"coin": "VeriCoin",
"code": "VRC",
"exchange": "BTC",
"last_price": "0.00008512",
"yesterday_price": "0.00009300",
"change": "-8.47",
"24hhigh": "0.00009450",
"24hlow": "0.00008050",
"24hvol": "13.153",
"top_bid": "0.00008063",
"top_ask": "0.00008591"
}
]
I just want to pull bits off this information out and assign them to variables. I use the below code with another near identical JSON output and it works fine.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
//GET 'LAST BID' INFO
$lastBid = $json->code;
The previous raw JSON that works with the above code looks exactly the same, except for not being encased in '[...]' as the Mintpal one is.
{
"success": true,
"message": "",
"result": [
{
"MarketName": "BTC-LTC",
"High": 0.01126000,
"Low": 0.01060000,
"Volume": 442.30927821,
"Last": 0.01061100,
"BaseVolume": 4.86528601,
"TimeStamp": "2014-08-27T13:49:03.497",
"Bid": 0.01051801,
"Ask": 0.01061100,
"OpenBuyOrders": 50,
"OpenSellOrders": 116,
"PrevDay": 0.01079000,
"Created": "2014-02-13T00:00:00"
}
]
}
Any ideas on why I can't read the information this time round?
If you either did a var_dump() or a print_r() of your $json variable you should see that it is now an array starting at element 0 containing all the unique json elements.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
pR($json);
//GET 'LAST BID' INFO
$lastBid = $json->code;
function pR($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}
That yielded:
Array
(
[0] => stdClass Object
(
[market_id] => 152
[coin] => VeriCoin
[code] => VRC
[exchange] => BTC
[last_price] => 0.00008512
[yesterday_price] => 0.00009300
[change] => -8.47
[24hhigh] => 0.00009300
[24hlow] => 0.00008050
[24hvol] => 12.968
[top_bid] => 0.00008065
[top_ask] => 0.00008585
)
)
I have JSON that looks like this (shortened for readability):
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
I have a PHP variable that is equal to one of the three ids. I need to search the JSON for the id and return the localized name. This is what I’m trying so far.
$heroid = $myplayer['hero_id'];
$heroes = file_get_contents("data/heroes.json");
$heroesarray = json_decode($heroes, true);
foreach ($heroesarray as $parsed_key => $parsed_value) {
if ($parsed_value['id'] == $heroid) {
$heroname = $parsed_value['localized_name'];
}
}
Easy. Just use json_decode(). Explanation follows the code at the bottom.
// First set the ID you want to look for.
$the_id_you_want = 2;
// Next set the $json.
$json = <<<EOT
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
EOT;
// Now decode the json & return it as an array with the `true` parameter.
$decoded = json_decode($json, true);
// Set to 'TRUE' for testing & seeing what is actually being decoded.
if (FALSE) {
echo '<pre>';
print_r($decoded);
echo '</pre>';
}
// Now roll through the decoded json via a foreach loop.
foreach ($decoded as $decoded_array_key => $decoded_array_value) {
// Since this json is an array in another array, we need anothe foreach loop.
foreach ($decoded_array_value as $decoded_key => $decoded_value) {
// Do a comparison between the `$decoded_value['id']` and $the_id_you_want
if ($decoded_value['id'] == $the_id_you_want) {
echo $decoded_value['localized_name'];
}
}
}
Okay, the reason my first try at this did not work—and neither did yours—is your JSON structure was nested one more level deep that what is expected. See the debugging code I have in place with print_r($decoded);? This is the output when decoded as an array:
Array
(
[heroes] => Array
(
[0] => Array
(
[name] => antimage
[id] => 1
[localized_name] => Anti-Mage
)
[1] => Array
(
[name] => axe
[id] => 2
[localized_name] => Axe
)
[2] => Array
(
[name] => bane
[id] => 3
[localized_name] => Bane
)
)
)
First you have an array to begin with which could equate to $decoded[0] and then below that you have another array that equates to $decoded[0]['heroes'] and then in there is the array that contains the values which is structured as $decoded[0]['heroes'][0], $decoded[0]['heroes'][1], $decoded[0]['heroes'][2].
But the key to solving this was the print_r($decoded); which helped me see the larger structure of your JSON.
json_decode() takes a JSON string and (if the second parameter is true) turns it into an associate array. We then loop through this data with a foreach until we find the hero you want.
$json = ''; // JSON string
$data = json_decode($json, true);
foreach($data['heroes'] as $hero) {
if($hero['id'] === 2) {
var_dump($hero['localized_name']);
// Axe
// This will stop the loop, if you want to keep going remove this line
break;
}
}