Parsing JSON with PHP array/object confusion - php

I am trying to parse this JSON data to print on a fanpage I am working on.
If you look at that JSON link, you will see that the structure is [{key:value,key:value,key:value}]. I recently learned how to parse JSON with a slightly different structure like this JSON file, where the data structure is {"identifier":[{key:value,value,value,value,value}{key:value,value...}]}
Here is my code I am attempting:(I have tried about 10 variations of this with explodes for the commas too)
<?php
$json = file_get_contents('http://live.nhl.com/GameData/SeasonSchedule-20152016.json');
$json = json_decode($json, TRUE);
foreach($json as $d){
$estTime = $d['est'];
echo $estTime;
?>
As I said, I had some success with that other structure of JSON I linked by doing this:
$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');
$json = json_decode($json, TRUE);
$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];
foreach($skaterData as $d){
$stats = explode(',', $d['data']);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];
Edit: JSON data successfully parsed

The only thing wrong with your code is that you are missing the closing curly bracket to your foreach.
I would strongly recommend paying attention to the error messages you get, often they will let you easily solve the problem. If your server does not display them in the browser (this is usually a good thing on live sites), you will find them in an error log somewhere on the server.
Additionally you may want to use a proper editor with linting (what is linting), which would probably have immediately notified you of this omission one way or another. One such free tool is Atom.

Related

Use PHP to parse INI file and run JSON_DECODE

I'm looking to get some input on how to make modular code that performs a PHP parse_ini_file and then uses the returned values to run JSON decodes.
I have a BACnet API that returns a JSON structure for BACnet points in an automation system. I wrote the following code to decode the JSON data to return just the "present-value" field and then I display the value on a webpage.
<?php
$url = "http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "<b>Room temperature</b>: ". $json_data["present-value"]. " DEG F";
;?>
This works well but I want to make this code modular so it can be used for many other points.
I created an INI file with a list of other points and the URL that contains the JSON data from the API.
## BACnet Configuration File
# BACnet Object URLs from WACNET Browser API
[bacnet]
SEA_RMT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0
SEA_SRV_SEA_SV1_01_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.3
SEA_SRV_SEA_SV1_02_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.4
SEA_SRV_SEA_SV1_03_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.5
What I'd like to do is use the INI file to get the present value of each point in the list and then create a variable that is the name of the point and set it equal to the "present-value" field. Then I can reference the point using the PHP variable on the HTML page like this:
<?php echo "$SEA_SRV_SEA_SV1_01_EXHT";?>
I started with the code below but it doesn't work.
<?php
// Parse the settings file
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini');
// Parse the keys to variables and add data
foreach ($bacnetini as $key => $value) {
$url = $value;
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$$key = $json_data;
}
?>
I'd love to get some other opinions on the best way to accomplish this since I don't really know where to go from here.
I've looked through these other Stack Overflow questions but I don't know how to get the pieces to all fit together.
Parsing a config file in php to variables
Get JSON object from URL
Why not try something like this instead? This will allow you to create other sections in your INI file that won't affect your script.
<?php
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini', true);
$data = array();
foreach ($bacnetini['bacnet'] as $key => $url) {
$data[$key] = json_decode(file_get_contents($url), true);
}
var_dump($data['SEA_SRV_SEA_SV1_01_EXHT']);
?>

Displaying information from JSON request

For the sake of having you guys being able to read what I'm doing, I will post this with the api key and then edit it after.
How do I display the information from this url?
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=UItqDZuHOsM&key=AIzaSyAQ26GN-removedapikey
I am using this code, but I don't understand the correct way to grab the json stuff. I've tried tons of different ways.
$vidkey = $vid_row['youtube_id'];
$apikey = "removed";
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json = json_decode($json_output, true);
//video title
$you_title = $json['snippet']['title'];
I guess I don't understand the hierarchy of it all.
Use Below code to get Title :
$vidkey = $vid_row['youtube_id'];
$apikey = "**********";
$json_output = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$vidkey&key=$apikey");
$json = json_decode($json_output, true);
echo $json['items'][0]['snippet']['title'];
Try do to a print_r($json) to understand what you're exactly doing. But just navigate in it as an object. In the current case just do:
$json['items'][0]['snippet']['title'];
But if you want to do it with a more easy way to do it (object way), just remove the true from your json_decode function
$json->items[0]->snippet->title;

accessing $_POST array variables in php

I'm able to access my $_POST array values, but can't seem to get the correct syntax for returning only the "data" part of the array. If I run var_dump($_POST["attributes"]);, I receive the following in the response callback(which is exactly what I expected):
string '{
"device_maker" = unknown;
"device_model" = Simulator;
"first_visit" = "1387478168.109";
"last_visit" = "1388358490.638";
latitude = "37.78583526611328";
locale = en;
longitude = "-122.4064178466797";
"opted_in" = 1;
"opted_out" = 0;
"os_platform" = "iPhone OS";
"os_version" = "7.0.3";
"this_visit" = "1387478168.109";
"user_id" = 1;
}' (length=389)
If I try to access any one of the attributes separately, like var_dump($_POST["attributes"]["device_model"]);, all I get in return is string '{' (length=1). I'm apparently missing a key idea on parsing this data. How do I parse "attributes" so I can place each one of the listed values into an insert statement(I've got that part ready to go once I get the data)? Granted, my php is very rusty. So I may be overlooking something obvious.
It's frustrating to see the data I need and not know how to correctly access it. So, any help is appreciated. Please ask if you need clarification.
Apparently the string being retrieved in your POST is not valid JSON. If you can't replace the values being sent to the server, you can always do a (dirty) workaround:
First, replace some characters to make it a valid json:
$jsonStr = str_replace('=', ':', $_POST["attributes"]);
$jsonStr = str_replace(';', ',', $jsonStr);
$jsonStr = str_replace(',}', '}', $jsonStr);
Then we can try to parse it using the json_decode function:
$jsonArray = json_decode($jsonStr);
Now you can access it as a regular associative array, e.g.:
echo $jsonArray['device_model'];
What you show here looks like JSON encoded data - it's a single string so there is no $_POST["attributes"]["device_model"].
You can access the data embedded in the attributes variable by converting it from JSON:
$a_string='{
"device_maker" = unknown;
"device_model" = Simulator;
"first_visit" = "1387478168.109";
"last_visit" = "1388358490.638";
latitude = "37.78583526611328";
locale = en;
longitude = "-122.4064178466797";
"opted_in" = 1;
"opted_out" = 0;
"os_platform" = "iPhone OS";
"os_version" = "7.0.3";
"this_visit" = "1387478168.109";
"user_id" = 1;
}';
// or $astring=$_POST['attributes']
$data=json_decode($a_string);
print $data['device_model'];
....but you need to verify the origin of the data - if it' not JSON, then this will break at some point.

JSON PHP: Is this the correct way?

I just wanted some input about my use of JSON.
<?php
header('Content-Type: text/plain');
//results
$results = array();
for($i=0;$i<20;$i++)
{
$result = array();
$result['name'] = 'Test Season '.ceil(($i+1)/13).' Episode '.(($i%13)+1);
//$result['torrent'] = 'https://www.example.com/?id='.$i.'&key='.uniqid();
$result['torrents'] = array();
$c = mt_rand(1,4);
for($j=0;$j<$c;$j++)
{
$torrent = array();
$torrent['url'] = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent['codec'] = $j%2 == 0 ? 'xvid' : 'h264';
$torrent['resolution'] = '720p';
$result['torrents'][] = $torrent;
}
$results[] = $result; //push
}
echo json_encode($results);
?>
This is just some test code, not an actual implementation. Am I using JSON correctly and too the fullest? Or is some better method of doing this?
I have legal torrents that I'd like to do some JSON with.
Torrents are grouped by name which contain multiple torrents (actual links to data). And other information such as codec etc.
This is my first time actually outputting JSON, would XML be better?
Are there any guides on this topic (hopefully not entire books)?
Thanks.
What you doing is right. I like to use the StdClass to make objects rather than key value arrays, just cause it looks sexier! E.g.
$torrent = new StdClass();
$torrent->url = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent->codec = $j%2 == 0 ? 'xvid' : 'h264';
$torrent->resolution = '720p';
$result['torrents'][] = $torrent;
As you say you don't need to read a whole book on the matter, I would have a look here http://php.net/manual/en/book.json.php to get to grips with the basics of JSON.
In terms of JSON vs XML, I find it far easier to represent data as JSON as it is easier to fetch the specific data you want much in the same way you can access the info in a stdClass object.
[EDIT]
And as Stefan Gehrig says make sure you define your content type as "application/json".
Absolutely fine. You could only change the MIME type to be RFC 4627 compliant though: application/json.

A weird result, as a result of this PHP script

require_once 'include/BestBuy/Service/Remix.php';
$skuid = rawurldecode($_GET['skuid']);
$apiKey = 'tfvs7h89pwn4pzmyj9nxemmg'; // Your API key
$remix = new BestBuy_Service_Remix($apiKey);
$result = $remix->product('$skuid','json')
->show(array('url'))
->query();
$data = json_decode ($result, true);
$feed = $data['url'];
print <<< FEEDS
$feed
FEEDS;
When I put this script into my page, the $feed will echo the current URL.
But when I manually supply the script with an integer, replacing ($skuid) it will be successful.
It's really weird, But I think it has something to do with me using a variable in that specific array.
And it is also weird, because It was working before I re arranged some of the HTML.
I'm trying to approach this problem the most logical way.
Please help.
Thanks.
should you have $skuid in quotes? I would expect:
$result = $remix->product($skuid,'json')
rather than
$result = $remix->product('$skuid','json')

Categories