How to navigate the JSON hierarchy with PHP? - php

I am building a weather application that decodes a JSON file (found here: http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric)
The problem I am running into is navigating the JSON file in my PHP code to correctly select the tempature.
I need to do list->1->main->temp but this pulls up a number error in PHP. How do I correctly set the navigation?
echo "<form id='searchform' method='POST' action='https://projekt2-sofiamusick.c9users.io/wordpress/prognos/'>
Search: <input type='text' name='searchquery' placeholder='Search the forum' />
<input class='sendbutton_search' type='submit' name='search' value='>>' />
</form>";
if (isset($_POST['search'])){
$cityz = $_POST['searchquery'];
echo "<br>";
echo "<div id=apithing>";
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=$cityz&appid=77f5e3fbc99649054660f82f871220f4&units=metric");
$jsonObject = json_decode($data, JSON_NUMERIC_CHECK);
json_encode( array( 'list' => (int)$jsonObject ) );
$list = $jsonObject->list;
$number = $jsonObject->'1';
$mains = $jsonObject->main;
echo $mains;

If you use JSON_NUMERIC_CHECK, your data present as array.
If you want get first element, just use $jsonObject['list'][0]
Without JSON_NUMERIC_CHECK, your data present as stdClass, and first element you can get with $jsonObject->list{0}

You can achieve it like this
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric");
$jsonObject = json_decode($data);
if($jsonObject->cod == '200' && count($jsonObject->list) > 0){
foreach ($jsonObject->list as $jlk => $jlv) {
$dt = $jlv->dt;
$main = $jlv->main;
// your rest of logic
}
}
If you want you can see your data like this:
echo '<pre>';
var_dump($jsonObject);
echo '</pre>';
die;
Where you will see object, means you have to use "->" to access, and where you see array there use key of array to fetch that value.
Please feel free to ask, if any other doubt.

Related

how to echo fixer.io json php

Hi I'm trying get a json from fixer.io and then for each rates echo it but cant get it to work.
the code are
<?php
function usd(){
echo 'HEJ test';
$fixer_access_key = my_access_key;
$url= 'https://data.fixer.io/api/latest?access_key=' . $fixer_access_key;
echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
echo $url . "<br>";
echo 'printing json foreach <br>';
foreach($data as $obj){
echo '...';
$prefix = $obj;
echo $prefix;
echo '<br>';}
echo 'done printing json foreach';
}
usd(); ?>
and the result are:
https://data.fixer.io/api/latest?access_key=my_fixer_key
printing json foreach
done printing json foreach
instead of
$data = json_decode($json);
use
$data = json_decode($json, true);
This should allow foreacha to works - however you will only see first level of json object keys (not nested ones). The second parameter of json_decode change result from object to array.
You will also need to change foreach - to following: foreach($data as $key => $obj) and inside it echo $obj to echo $key;.
Here is simplified working example.
ALTERNATIVE SOLUTION
If working foreach is not your goal but rather pretty printed json, then instead use following code:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;

converting json branched array to php object

In below code, I want to display get_data using echo but not able to decode/display branched array. So, My question is how to convert branched array to PHP object.
Json Response :
{"status":1,"msg":"fetched Succesfully","user_data":{"d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba":{"name":"PRATYUSH","user_year":"2013","get_data":"d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba","is_active":1,"data_no":"ghjgjj2XXXXXXoioo7","user_bin":"77","is_exp":"N"}}}
PHP CODE :(after using curl)
$response = json_decode($o,true);
$status=$response["status"];
$msg=$response["msg"];
$user_data=$response["user_data"][0]["get_data"];
RESULT:
echo $status;//(working)
echo "<br>";
echo $msg;//(working)
echo "<br>";
echo $user_data;//(Not working)
echo User_data is not working.
So you want to get value of get_data. If d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba is not known, try this way.
$user_data_arr=$response["user_data"];
foreach($user_data_arr AS $user_data_obj)
{
echo $user_data_obj['get_data'];// here is your desired value
}
Using foreach loop, you do not have to find index and you can get values easily.
Full Code
$response = json_decode($o,true);
$status=$response["status"];
$msg=$response["msg"];
$user_data="";
$user_data_arr=$response["user_data"];
foreach($user_data_arr AS $user_data_obj)
{
$user_data = $user_data_obj['get_data'];// here is your desired value
}
echo $status;
echo "<br>";
echo $msg;
echo "<br>";
echo $user_data;//will work
Change
$user_data=$response["user_data"][0]["get_data"];
to this
$user_data=$response["user_data"]["d91c2d21af80002a3dd6ffc76f62bb9f89b6e0ba"]["get_data"];

array to xml or xspf make xspf file for embed vlc lugin playlist

i am trying input check box list current folder .mp3 get using gob function glob_grace list the audio files using check box then
get array check box values make xspf file using php
i write code all for array to xml
but small error please anyone tell me what error and the error where occurred !
<?php
foreach (glob("*.{mp3,mp4}", GLOB_BRACE) as $filename) {
$values = $filename ;
echo "<form action='p.php' method='POST'>";
echo "<input type='checkbox' name='foo[]' value='$values'>$values <hr>";
}
echo "<input type='submit' name='submit' value='Submit'>";
echo "</form>";
?>
it will go to next page below
<?php
$g = $_POST['foo'];
$cnt = count($g);
//function definition to convert array to xml
function array_to_xml($array, &$xml_user_info) {
for ($i=0 ; $i < $cnt ;$i++)
{
$track = $xml_user_info->addChild('track');
$track->addChild("location",$array[$i]);
}
}
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><trackList></trackList>");
//function call to convert array to xml
array_to_xml($g,$xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xspf');
//success and error message based on xml creation
if($xml_file){
echo 'XML file have been generated successfully.';
}else{
echo 'XML file generation error.';
}
?>
please give me answer solution working code
thanks in advance
If glob("*.{mp3,mp4}", GLOB_BRACE) returns an array with more than 1 item, you are generating the <form action='p.php' method='POST'> tag multiple times.
Maybe you could move the form declaration to outside of the foreach.
If I submit the form and I load the p.php, I get this Notice:
Notice: Undefined variable: cnt
You are using $cnt = count($g); to count the items, but you could also pass this $g and count its items inside the function array_to_xml.
I think that if you want to get the value from $_POST['foo'], you should first check if it is a POST and then check if the $_POST['foo'] is set.
Maybe this setup can help you:
<?php
//function definition to convert array to xml
function array_to_xml($array, &$xml_user_info)
{
for ($i = 0; $i < count($array); $i++) {
$track = $xml_user_info->addChild('track');
$track->addChild("location", $array[$i]);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['foo'])) {
$g = $_POST['foo'];
//creating object of SimpleXMLElement
$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><trackList></trackList>");
//function call to convert array to xml
array_to_xml($g, $xml_user_info);
//saving generated xml file
$xml_file = $xml_user_info->asXML('users.xspf');
//success and error message based on xml creation
if ($xml_file) {
echo 'XML file have been generated successfully.';
} else {
echo 'XML file generation error.';
}
}
}
?>
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><playlist></playlist>');
$trackList = $xml->addChild('trackList');
foreach ($_POST['files'] as $video) {
$track = $trackList->addChild('track');
$track->addChild('location', 'file://'.$tmp_dir.'/'.$video['path']);
$track->addChild('title', $video['name']);
}
file_put_contents('playlist.xspf',$xml->asXML());

How can I parse this JSON with PHP?

How can I parse this JSON, which is supposed to display the items a user has in their Steam inventory.
I have tried this:
$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
echo $data;
It returns the same as just visiting the link. I can't get anything like this to work either:
$id = $json->type;
echo $type;
This is how to get type
$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->type;
}
$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
echo $data;
you are echoing $data that is your input (so you see the same as opening the link directly). To see if the json_decode is working fine you should print $json.
So instead of
echo $data;
use
echo '<pre>'
print_r($json);
echo '</pre>';
$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
Now $json has 2 objects.
you can access like.
$json->rgInventory;
$json->success;
if you want to fetch all data from $json->rgInventory;
foreach($json->rgInventory as $e){
//var_dump($e);
echo $e->id;
echo $e->classid;
echo $e->instanceid;
}
etc.

How do I print all POST results when a form is submitted? [duplicate]

This question already has answers here:
Print out post values
(11 answers)
Closed 6 years ago.
I need to see all of the POST results that are submitted to the server for testing.
What would be an example of how I can create a new file to submit to that will echo out all of the fields which were submitted with that form?
It's dynamic, so some fields may have a name/ID of field1, field2, field3, etc.
All the values are stored in the $_POST collection
<?php print_r($_POST); ?>
or if you want something fancier that is easier to read use a foreach loop to loop through the $_POST collection and print the values.
<table>
<?php
foreach ($_POST as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
?>
</table>
You could try var_dump:
var_dump($_POST)
Simply:
<?php
print_r($_POST);
//Or:
foreach ($_POST as $key => $value)
echo $key.'='.$value.'<br />';
?>
You may mean something like this:
<?php
$output = var_export($_POST, true);
error_log($output, 0, "/path/to/file.log");
?>
You could use something as simple as this
<?php
print_r($_POST);
?>
This would make it a bit more viewable:
<?php
echo str_replace(' ', ' ', nl2br(print_r($_POST, true)));
?>
You can definitely use var_dump, but you mentioned you are in front-end development. I am sure you would know this, but just as a reminder, use Firefox's Firebug or Chrome's / Internet Explorer's developers tool and check for the post. Post goes through hearders, and you should be able to check it from there too.
if (! function_exists('d'))
{
// Debugger
function d($var, $exit = 0)
{
// Only output on localhost
if ($_SERVER['HTTP_HOST'] != 'localhost')
{
return;
}
echo "\n[degug_output_BEGIN]<pre>\n";
echo var_export($var, 1);
echo "\n</pre>[degug_output_END]\n";
if ($exit)
exit;
}
}
// Call:
d($_POST);
Bonus: Check debug_backtrace() too add tracing to your debugging.

Categories