Related
I understand there are other similar posts about this, I am going out of my wits end here.
I have a few files with some JSON (all valid according to online validators, eg. jsonlint) - see EDIT below.
$contents = file_get_contents(DATA_PATH.'/'.$type.'.json');
$data = json_decode($contents, true);
echo var_dump($data);
Returns NULL
If I echo $contents, I do get output.
I'm not sure what is wrong? I understand file_get_contents gets it into a string, however, how do I get it in a valid JSON? Would using fopen() be any different?
I even added the JSON to a variable but had the same outcome... I must be stupid.
Note: Most JSON I'll get will be from an API, these file-based JSONs are for testing purposes.
Thanks.
EDIT: Sample json
{
"data": [{
"id": 1,
"name": "Albania",
"alpha2code": "AL",
"alpha3code": "ALB",
"capital": "Tirana",
"flag": "https://cdn.elenasport.io/flags/svg/1",
"region": "Europe",
"subregion": "Southern Europe",
"timezones": [
"UTC+01:00"
]
},
{
"id": 3,
"name": "Algeria",
"alpha2code": "DZ",
"alpha3code": "DZA",
"capital": "Algiers",
"flag": "https://cdn.elenasport.io/flags/svg/3",
"region": "Africa",
"subregion": "Northern Africa",
"timezones": [
"UTC+01:00"
]
}]
}
Your file might have a UTF-8 BOM which is not copied when you copy-and-paste your sample JSON to a (web based) validator. It's an invisible mark at the beginning of your file.
If you run echo bin2hex(file_get_contents(DATA_PATH.'/'.$type.'.json')) your file should begin with 7b, which is a {.
If it starts with efbbbf and then a 7b, there is a BOM. Either strip it out yourself or re-save your JSON without one using a text editor like Sublime Text which allows you to configure that.
For example. I want to get coordinates of all node buildings in bbox.
PHP
$queryBuildings="[out:json];node['building']({$y1},{$x1},{$y2},{$x2});out;";
$data = file_get_contents("http://overpass-api.de/api/interpreter?data={$queryBuildings}")
One element from result:
{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}
I want to get only lon and lat fields it's possible?
You can use skeleton print mode (out skel) which omits all tags, thus being slightly shorter. So your request should become: [out:json];node['building']({$y1},{$x1},{$y2},{$x2});out skel;
Currently csv output mode ([out:csv]) is the only mode where you can select the fields to be shown.
<?php
$data = '{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}';
$test = json_decode($data);
var_dump($test->lon);
First use json_decode to parse the response body:
$parsed_data = json_decode($data);
Then you can access the various fields like so:
$lat = $parsed_data->lat;
$lon = $parsed_data->lon;
I had a yaml file that I needed parsed into an array and I got that done. Now this array is huge. I only want a couple values...
X1, Y1, X2, Y2, owner, that's all I would like. If I can get them to be spit out into arrays nicely it would mean the world to me. (The owner must be the owner related to those X1, y1, x2, y2 values...
(They are are all related to each other) There are many x1,y1 in the array but they all come under headings... etc I don't know how to get them all...
Here is a look at what the array spits out... (Shortened because of filesize limit)
http://pastebin.com/PyH18mZv
Any help would be appreciated.
To Parse YAML you can use various available PHP parsers. i parsed your YAML by using Online YAML Parser and output the string in JSON. At The end required array values can be accessed by decoding the JSON.
*
please note i cut the string short just for example purpose
*
$arr='{
"Residences": {
"WorkArea": {"BlackList": {"Type": "BLACKLIST", "ItemList": []},
"EnterMessage": "Welcome %player to %residence, owned by %owner.",
"Areas": {
"main": {
"Y1": 217,
"X1": -6301,
"X2": -6306,
"Y2": 205,
"Z1": 3001,
"Z2": 2981
}
},
"Permissions": {"Owner": "cal9897","World": "VivaWorld"}
},
"caylyn55": {
"BlackList": {
"Type": "BLACKLIST",
"ItemList": []
},
"EnterMessage": "Welcome %player to %residence, owned by %owner.",
"StoredMoney": 0,
"IgnoreList": {
"Type": "IGNORELIST",
"ItemList": []
},
"LeaveMessage": "Now leaving %residence.",
"Subzones": {},
"Areas": {
"main": {
"Y1": 67,
"X1": 1220,
"X2": 1210,
"Y2": 64,
"Z1": 369,
"Z2": 360
}
},
"Permissions": {
"Owner": "caylyn55",
"PlayerFlags": {},
"GroupFlags": {},
"World": "VivaWorld"
}
}
},
"Version": 1,
"Seed": 1337068141
}';
Decode JSON
$a= json_decode($arr,true);
First Area Value get through
$a['Residences']['WorkArea']['Areas']['main']['Y1'];
and Second Area value
$a['Residences']['caylyn55']['Areas']['main']['Y1'];
if ['WorkArea'] AND ['caylyn55'] dynamic you can use this code
$b=array_values($a);
foreach($b as $values)
{
if(is_array($values)) {
foreach(array_keys($values) as $c){
echo $a['Residences'][$c]['Areas']['main']['Y1'];
}
}
}
You just need to add the complete reference to the data you're trying to ouput.
Example: echo $data['Residences']['WorkArea']['Permissions']['Owner'];
Something like this
$extracted = array_map(function ($residence) {
$r = $residence['Areas']['main'];
$r['owner'] = $residence['Permissions']['Owner'];
return $r;
}, $data['Residences']);
I'm trying to match a form supplied UTC time and form supplied event name string with an array read in from a file. The problem is that it seems to always match even when it shouldn't. The format of the file will always be constant, so I know I'll be looking for a value within double quotes, so after failing to get results with strpos(), I tried preg_match...and now match everything. Code and example output follow ($utc and $event_name)are already set and correct when we get here):
$match1 = "/\"{$utc}\"/";
$match2 = "/\"{$event_name}\"/";
print "Match Values: $match1, $match2<p>";
foreach($line_array as $key => $value) {
print "Value = $value<p>";
if ((preg_match($match1,$value) == 1) and (preg_match($match2,$value) == 1))
{
print "Case 1 - False<p>";
} else {
print "Contains targets: $value<p>";
//code to act on hit will go here
}
}
And here's what comes back:
Match Values: /"1371033000000"/, /"Another test - MkII "/
Value = { "date": "1357999200000", "type": "meeting", "title": "Plant and Animal Genome Conference, San Diego, CA", "description": "NCGAS to present at Plant and Animal Genome Conference, San Diego, CA", "url": "http://www.event1.com/" }
Contains targets: { "date": "1357999200000", "type": "meeting", "title": "Plant and Animal Genome Conference, San Diego, CA", "description": "NCGAS to present at Plant and Animal Genome Conference, San Diego, CA", "url": "http://www.event1.com/" }
Value = { "date": "1357693200000", "type": "meeting", "title": "Testing Addition", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
Contains targets: { "date": "1357693200000", "type": "meeting", "title": "Testing Addition", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
Value = { "date": "1371033000000", "type": "meeting", "title": "Another test - MkII", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
Contains targets: { "date": "1371033000000", "type": "meeting", "title": "Another test - MkII", "description": "This is a fake event.", "url": "http://pti.iu.edu" }
I should only be matching the last one, but they all match. I've been playing with the regex and can't seem to find the right magic.
Simplified it and got what I was after:
foreach($line_array as $key => $value) {
print "Value = $value<p>";
if (preg_match("/$utc/",$value) and preg_match("/$event_time/",$value))
{
print "Contains targets: $value<p>";
} else {
print "Case 1 - False<p>";
//code to act on hit will go here
}
}
But answer 2 got me in the right direction. Thanks, Ian!
You don't need to do anything weird inside a double-quoted string, just drop your variable in as is...
$match1 = "/$utc/";
$match2 = "/$event_name/";
I suspect your regexes are looking for zero-length strings.
Also, this line doesn't need so many parentheses...
if (preg_match($match1,$value) == 1 and preg_match($match2,$value) == 1) {
[...]
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP JSON decode - stdClass
I have a JSON file with a structure like this:
[{"key_mappings": "",
"screen2_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen2_thumb.png",
"video_url": "http://www.youtube.com/watch?v=S7MDxObgJxw",
"rating": "Teen",
"screen1_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen1_thumb.png",
"metascore": 43.63,
"height": 500,
"screen3_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen3_thumb.jpg",
"stage3d": false,
"screen3_url": "http://games.mochiads.com/c/g/siegius-arena/screen3.jpg",
"recommendation": 5,
"coins_revshare_enabled": null,
"category": "Fighting",
"screen4_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen4_thumb.png",
"uuid": "6789c7e3-fd27-345e-85d9-e6a58165ae57",
"author": "Juice-Tin",
"thumbnail_large_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_200x200.png",
"author_link": "https://www.mochimedia.com/community/profile/Juice-Tin",
"controls":
[["C", "Item"],
["V", "Spell"],
["X", "Heavy Attack"],
["Z", "Fast Attack"],
["fire", "na"],
["jump", "na"],
["movement", "arrow"]],
"languages": ["en"],
"swf_url": "http://games.mochiads.com/c/g/siegius-arena/Siegius%20Arena_.swf",
"recommended": true,
"game_tag": "e0e05c5c5fd1a61b",
"achievements_enabled": false,
"zip_url": "http://games.mochiads.com/c/g/siegius-arena.zip",
"screen1_url": "http://games.mochiads.com/c/g/siegius-arena/screen1.png",
"updated": "2012-10-25T15:47:01.953336-08:00",
"description": "Fight in arena battles and upgrade your gladiator in this Action-RPG about betrayal and revenge.",
"tags": ["siegius", "arena", "gladiator", "rome", "battle", "fight", "upgrade", "rpg", "fans", "en"],
"swf_file_size": 10142842,
"leaderboard_enabled": false,
"game_url": "http://www.mochimedia.com/games/siegius-arena",
"screen2_url": "http://games.mochiads.com/c/g/siegius-arena/screen2.png",
"slug": "siegius-arena",
"categories": ["Action", "Fighting"],
"instructions": "",
"name": "Siegius Arena",
"created": "2012-10-25T12:47:55.080005-08:00",
"control_scheme": "{\"C\": \"Item\", \"fire\": \"na\", \"jump\": \"na\", \"V\": \"Spell\", \"X\": \"Heavy Attack\", \"Z\": \"Fast Attack\", \"movement\": \"arrow\"}",
"popularity": 0,
"feed_approval_created": "2012-10-25T13:30:53.505710-08:00",
"coins_enabled": null,
"thumbnail_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_100x100.png",
"screen4_url": "http://games.mochiads.com/c/g/siegius-arena/screen4.png",
"alternate_url": "",
"resolution": "800x500",
"width": 800}]
Then, I have a foreach statement which adds the data to a MYSQL database:
foreach($result as $key => $value) {
if($value) {
mysql_query("INSERT INTO `games_db`.`Games` (`title`, `description`, `image`, `category`, `page`, `rating`, `width`, `height`, `tags`) VALUES ('$value->name', '$value->description', '/images/$pageid.jpg', '$category', '$pageid', '$value->rating', '$value->width', '$value->height', '$value->tags')")
}
My question is, What do I have to do to show and insert the tags from the JSON file? Currently, When I run this page, the data for the "tags" column just says "Array".
You can use json_decode() as so:
$jsonString = '[{"key_mappings": "", "screen2_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen2_thumb.png", "video_url": "http://www.youtube.com/watch?v=S7MDxObgJxw", "rating": "Teen", "screen1_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen1_thumb.png", "metascore": 43.63, "height": 500, "screen3_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen3_thumb.jpg", "stage3d": false, "screen3_url": "http://games.mochiads.com/c/g/siegius-arena/screen3.jpg", "recommendation": 5, "coins_revshare_enabled": null, "category": "Fighting", "screen4_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen4_thumb.png", "uuid": "6789c7e3-fd27-345e-85d9-e6a58165ae57", "author": "Juice-Tin", "thumbnail_large_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_200x200.png", "author_link": "https://www.mochimedia.com/community/profile/Juice-Tin", "controls": [["C", "Item"], ["V", "Spell"], ["X", "Heavy Attack"], ["Z", "Fast Attack"], ["fire", "na"], ["jump", "na"], ["movement", "arrow"]], "languages": ["en"], "swf_url": "http://games.mochiads.com/c/g/siegius-arena/Siegius%20Arena_.swf", "recommended": true, "game_tag": "e0e05c5c5fd1a61b", "achievements_enabled": false, "zip_url": "http://games.mochiads.com/c/g/siegius-arena.zip", "screen1_url": "http://games.mochiads.com/c/g/siegius-arena/screen1.png", "updated": "2012-10-25T15:47:01.953336-08:00", "description": "Fight in arena battles and upgrade your gladiator in this Action-RPG about betrayal and revenge.", "tags": ["siegius", "arena", "gladiator", "rome", "battle", "fight", "upgrade", "rpg", "fans", "en"], "swf_file_size": 10142842, "leaderboard_enabled": false, "game_url": "http://www.mochimedia.com/games/siegius-arena", "screen2_url": "http://games.mochiads.com/c/g/siegius-arena/screen2.png", "slug": "siegius-arena", "categories": ["Action", "Fighting"], "instructions": "", "name": "Siegius Arena", "created": "2012-10-25T12:47:55.080005-08:00", "control_scheme": "{\"C\": \"Item\", \"fire\": \"na\", \"jump\": \"na\", \"V\": \"Spell\", \"X\": \"Heavy Attack\", \"Z\": \"Fast Attack\", \"movement\": \"arrow\"}", "popularity": 0, "feed_approval_created": "2012-10-25T13:30:53.505710-08:00", "coins_enabled": null, "thumbnail_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_100x100.png", "screen4_url": "http://games.mochiads.com/c/g/siegius-arena/screen4.png", "alternate_url": "", "resolution": "800x500", "width": 800}]';
$jsonObject = json_decode($jsonString);
foreach ($jsonObject->tags as $tag) {
echo $tag . PHP_EOL;
//Do something
}
If you use less than PHP 5.2.0, you can use the JSON PECL Extension
I should also add that you shouldn't use the mysql functions any more - they're deprecated. See: Why shouldn't I use mysql_* functions in PHP?
use json_decode():
json_decode — Decodes a JSON string
$jsonObject = json_decode($string); // returns an object
or:
$jsonArray = json_decode($string, true); // if second argument is true, returned object will be converted to an associative array
Edit:
as suggested by #nickhar: NOTE: You need PHP 5.2.0 or above to use json_decode()
Or one of the emulations floating around – #mario