PHP Decoding JSON - Null Output - php

I have probably spent all day trying to figure this out. I have read multiple questions here on stack and also have been reading articles and checking on documentation, but I can't seem to figure out why this batch of code just produces a null output. Am I missing brackets, calling something wrong, ect?
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
refresh_requency => 30
);
echo json_encode($array);
?>
Again what I'm asking is can someone point out to me or tell me what I'm doing wrong. Is it my server that's just not handling the data correctly? That could be a possibility.
One other thing I've tried is to just print out $temp and/or the other variable like $str. When I do that though they don't even show up so that's what I think my problem is just not sure how to fix it.
Update
I've come to the conclusion that it's my web hosting service. As if I add var_dump($json) I get a null output null output.
Also to confirm that its my webhost if I run error_reporting(E_ALL); ini_set('display_errors', 1); it points to the file php.ini not allowing outgoing connections. I edited that same file on my local home server(raspberry pi) ran the same file and it works fine.

Below is the working solution for your above code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
When I executed your code, I found 2 problem into your code snippet:
1) You were trying to use object of type stdClass as array.
Solution:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json->main->temp_min;
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
2) You did not put array key into quotes:
$array = array(
"content" => $content,
refresh_requency => 30
);
It should be :
$array = array(
"content" => $content,
"refresh_requency" => 30
);

Access $temp like this
$temp = $json->main->temp_min;
you will get the desired output.
Also, you need to allow allow_url_fopen in your php.ini config file. Some hosts disallow it for security reasons

$json = json_decode($str, true);
You need second argument to convert json string into associative array instead of the object. And you are trying to use array ($json['main']['temp_min']), not object. Also
$array = array(
"content" => $content,
"refresh_requency" => 30
);
The code looks like
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$content = $json['main']['temp_min'];
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
And result is http://codepad.viper-7.com/euBNAk :
{"content":44.6,"refresh_requency":30}

The second parameter of json_decode() is assoc (associative). By default it is 0. When it is 0 (default) the json_decode() will return an object, not an array. That's why you are unable to access temp_min by using $json['main']['temp_min'];
However If you use with the value 1 as second parameter, the function will return an array. Parameter 1 means setting associative to 1 (true). So use $json = json_decode($str, true); instead of $json = json_decode($str);. You will be able to access with $json['main']['temp_min']; now.
Also you forgot double quote on line 13 (refresh_requency). Goodluck.
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);

Just want help
I change your code like this and that be correctly
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, TRUE); // Wrong here
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30 // And wrong here, it's must string
);
echo json_encode($array);
?>
More information about json decode in php to array or object http://php.net/manual/en/function.json-decode.php

Related

Adding object to array also adds 'null'

I send the following data to my php file via ajax:
JSON.stringify({test1: '1', test2: '2'})
I would like to write this data to my JSON FILE content.json containing an empty array
[]
I only want to add the content though if it is not there, yet. This is my PHP code:
$jsonStringObject = file_get_contents("php://input");
$phpObject = json_decode($jsonStringObject);
$newJsonStringObject = json_encode($phpObject);
header('Content-Type: application/json');
$jsonString = file_get_contents('content.json');
$data = (array) json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
It almost works. Something is wrong with the way the data is added to the array because when I call the function for the first time, it updates content.json to
[null,{"test1":"1","test2":"2"}]
On calling the function again, it adds the object again despite the if-statement:
[null,{"test1":"1","test2":"2"},{"test1":"1","test2":"2"},{"test1":"1","test2":"2"}]
Can anyone help me to spot the mistake?
You're comparing apples and oranges (or rather objects to arrays).
Make sure you decode all json as arrays:
$jsonStringObject = file_get_contents("php://input");
// Added true as second argument to get it bas as an array
$phpObject = json_decode($jsonStringObject, true);
$jsonString = file_get_contents('content.json');
// Removed the (array) since the second argument literally means "return as array"
$data = json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
Demo: https://3v4l.org/rnCn5

I'm writing json array to file. I'm getting [{ , , }][{ , , }][{ , , }]. I need this output [{ , , },{ , , },{ , , }]. Any Suggestions?

I'm writing json array to the file. I'm getting [{ , , }][{ , , }][{ , , }]. I need this output [{ , , },{ , , },{ , , }].
I'm not adding json items to the array, instead creating multiple arrays.
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "a+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
//output
[{"name":"ggg","qty":"ff","price":"ff"}]
[{"name":"ggg","qty":"ff","price":"ff"}]
//How to achieve this
[{"name":"ggg","qty":"ff","price":"ff"},
{"name":"ggg","qty":"ff","price":"ff"}]
I think you are write to the file after each post request and your array $a will only have the post array data.
that's why you getting your file at the end look like that
//output
[{"name":"ggg","qty":"ff","price":"ff"}]
[{"name":"ggg","qty":"ff","price":"ff"}]
so to fix this issue and get your data in the right format , each time you want to write to your file , first you need to load the data from the file and then merge it to your array $a and then write it again.
so this code should works in your case
//load file data
$data = file_get_contents("newfile.json");
$a = json_decode($data, true);
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "w+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
I initialized $a with the data in file and change mode in fopen to w+
Try loading the data from the file into a, appending new_array to said data, then writing this new json list object into the file.
Managed to merge this together. There is most likely a better solution
array_merge in official PHP documentation
json_decode in official PHP documentation
$a = [{"name":"ggg","qty":"ff","price":"ff"}];
$b = [{"name":"ggg","qty":"ff","price":"ff"}];
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
or
$r = [];
foreach(json_decode($a, true) as $key => $array){
$r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);
use below code, hope it will meet your output:
$data = file_get_contents("newfile.json");
$a = explode("][", $data);
$x = '';
foreach($a as $y){
$x .= $y.",";
}
echo trim($x, ",");
There problem is with the appending data to newfile.json, Here a list already appended as a text, and after that whenever we append more text, it is appended as a text, not a json object, Therefore kindly try the following code along with your existing code:-
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// reading data from .json file
$data = file_get_contents('newfile.json');
// creating an array of object from the text of .json file
$tempArray = json_decode($data);
// adding our new object to array
array_push($tempArray, $new_data);
// creating json representation of the array
$jsonData = json_encode($tempArray);
// writing json representation to the .json file
file_put_contents('newfile.json', $jsonData);
Hope this will help.
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
$lastIndex = count($data);
$data[$lastIndex] = $new_data;
$myfile = fopen("newfile.json", "w") or die("Unable to open file!");\
fwrite($myfile, json_encode($data));
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
print_r($data);

Read JSON Data Have Token With PHP

How can I read a JSON data response using php?
This is Code :
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
and give me this json data :
{
"original": "This sentnce has some probblems.",
"suggestion": "This sentence has some problems.",
and ...
}
I want to return "suggestion" in a url with $
this is an example :
$user_id = '123456789'
$mytext = '?' // I WANT RETURN "suggestion" HERE !
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
You can use json_decode().
See:
http://php.net/manual/en/function.json-decode.php
You just need to do:
$response = json_decode($response,1);
echo $response['suggestion'];
Setting the second parameter of json_decode() to 1 (true) will return an associative array of the JSON data.
If you want to include it in a URL using your code example:
$user_id = '123456789'
$json = json_decode($response,1);
$mytext = $json['suggestion'];
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$mytext
file_get_contents($url);
Use json_decode to convert json_response to array.Add second parameter of 'true' to make it an array that you should be familiar with.
Access suggestion variable by specifying it.
$response = Unirest\Request::get("https://montanaflynn-spellcheck.p.mashape.com/check/?text=This+sentnce+has+some+probblems.",
array(
"X-Mashape-Key" => "MY X-Mashape-Key",
"Accept" => "application/json"
)
);
$data=json_decode($response,true);
$url = 'https://api.telegram.org/mytoken/sendMessage?chat_id='.$user_id.'&text='.$data['suggestion'];
echo $url;

Sending JSON Array via PHP (Campaign Monitor)

I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}

How to generate JSON data with PHP?

CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.php code
<?php
$sql=mysql_query("select * from Posts limit 20");
echo '{"posts": [';
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
echo '
{
"title":"'.$title.'",
"url":"'.$url.'"
},';
}
echo ']}';
?>
I have to generate results.json file.
To generate JSON in PHP, you need only one function, json_encode().
When working with database, you need to get all the rows into array first. Here is a sample code for mysqli
$sql="select * from Posts limit 20";
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);
then you can either use this array directly or make it part of another array:
echo json_encode($posts);
// or
$response = json_encode([
'posts' => $posts,
]);
if you need to save it in a file then just use file_put_contents()
file_put_contents('myfile.json', json_encode($posts));
Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).
Here is a working Example:
<?php
// data stored in an array called posts
$posts = Array (
"0" => Array (
"id" => "01",
"title" => "Hello",
),
"1" => Array (
"id" => "02",
"title" => "Yoyo",
),
"2" => Array (
"id" => "03",
"title" => "I like Apples",
)
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>
Insert your fetched values into an array instead of echoing.
Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.
If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo json_encode($array);
Then in your script set the path to the file my_json.php
Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.
$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT)); // here it will print the array pretty
fclose($fp);
Hope it will works for you....
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
First, you need to decode it :
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
copy
Use PHP's json methods to create the json then write it to a file with fwrite.

Categories