I'm getting null (blank page) from this:
api.php code:
$json_data = array(
'status' => 'failed',
'version' => '0.0.5'
);
header("Content-type: application/json");
echo json_encode($json_data, JSON_PRETTY_PRINT);
getapi.php code:
$json_file = file_get_contents("http://domain.com/api.php");
$json_data = json_decode($json_file);
print_r($json_data);
$json_file = file_get_contents("http://domain.com/api.php");
echo $json_file; //{"status":"failed","version":"0.0.5"}
$json_data = json_decode($json_file);
print_r($json_data); // blank page
Another answer I would like to submit is the one of trying to debug your json string since you have already told us that the content is pulled in correctly by your file_get_contents()
I have the following script from the PHP.net documentation on json_last_error()
echo 'Decoding: ' . $string;
json_decode($json_file);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
Edit
It looks like you are having trouble with your character set. Try forcing utf-8 as follows.
Change:
header("Content-type: application/json");
To:
header('Content-Type: application/json; charset=utf-8');
The problem is probably with your PHP.ini file and your PHP settings not allowing you to acces remote urls.
The setting you are looking for is allow_url_fopen.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.
If you have access to your php.ini file though, I would suggest editing it.
Some reading
Documentation on allow_url_fopen
By the first you should be sure that your api.php is available through HTTP.
open URL http://domain.com/api.php in some browser to check, you must see the available response.
If you still see blank page then probably your webserver is not configured properly or api.php file store in not public folder aka. public_html or web.
Run following command:
$ php -i|grep 'allow_url_fopen'
allow_url_fopen => On => On
Also please check your PHP configuration, option allow-url-fopen should be set to true.
Also please pay attention that constant JSON_PRETTY_PRINT available since PHP 5.4.0
Next snippet will help you to troubleshoot, place it on the top of your script, but don't forget to remove them after:
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
Try to use function above instead json_decode, it include utf8 fix inside
function parseJson($content, $options = true)
{
$content = fixUtf8String(trim($content));
$decoded = json_decode(utf8_decode($content), $options);
if (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
switch ($jsonLastErr) {
case JSON_ERROR_DEPTH:
throw new Exception('JSON Decoding failed: Maximum stack depth exceeded');
case JSON_ERROR_CTRL_CHAR:
throw new Exception('JSON Decoding failed: Unexpected control character found');
case JSON_ERROR_SYNTAX:
throw new Exception('JSON Decoding failed: Syntax error');
default:
throw new Exception('JSON Decoding failed');
}
}
return $decoded;
}
function fixUtf8String($s)
{
if (empty($s)) {
return $s;
}
$s = preg_match_all(
"#[\x09\x0A\x0D\x20-\x7E]|
[\xC2-\xDF][\x80-\xBF]|
\xE0[\xA0-\xBF][\x80-\xBF]|
[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|
\xED[\x80-\x9F][\x80-\xBF]#x", $s, $m
);
return implode("", $m[0]);
}
Related
"op=add&item={"firstName":"test","lastName":"test","email":"test%40test.com","password":"test"}"
I'm passing the JSON body above to my PHP backend and when trying to use json_decode on it, it results in null. I've used json_last_error() and it states there is a syntax issue. Using jsonlint.com, it gives me this error:
Error: Parse error on line 1:
"op=add&item={"firstName ":"test "
---------------^
Expecting 'EOF', '}', ':', ',', ']', got 'undefined'
I've tried troubleshooting this error but haven't been able to get a successful response. Can someone describe what the issue could be?
For json_decode() to work, it requires a string.
Looking at you syntax, it seems the outer quotes aren't correct.
Yours:
"op=add&item={"firstName":"test","lastName":"test","email":"test%40test.com","password":"test"}"
As they should be:
'op=add&item={"firstName":"test","lastName":"test","email":"test%40test.com","password":"test"}'
If you use single quotes, it's a correct string. Which can be decoded.
Your "body" isn't a JSON string, only the item parameter content looks like one. Take that content and pass to the function json_decode.
Example:
json_decode($_GET['item']);
this is a useful function to debug json issues
function json_validate($string){
// decode the JSON data
$result = json_decode($string);
// switch and check possible JSON errors
switch (json_last_error()) {
case JSON_ERROR_NONE:
$error = ''; // JSON is valid // No error has occurred
break;
case JSON_ERROR_DEPTH:
$error = 'The maximum stack depth has been exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Invalid or malformed JSON.';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Control character error, possibly incorrectly encoded.';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error, malformed JSON.';
break;
// PHP >= 5.3.3
case JSON_ERROR_UTF8:
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
break;
// PHP >= 5.5.0
case JSON_ERROR_RECURSION:
$error = 'One or more recursive references in the value to be encoded.';
break;
// PHP >= 5.5.0
case JSON_ERROR_INF_OR_NAN:
$error = 'One or more NAN or INF values in the value to be encoded.';
break;
case JSON_ERROR_UNSUPPORTED_TYPE:
$error = 'A value of a type that cannot be encoded was given.';
break;
default:
$error = 'Unknown JSON error occured.';
break;
}
if ($error !== '') {
// throw the Exception or exit // or whatever :)
exit($error);
}
// everything is OK
return $result;
}
So, i'm creating php page that sends JSON data to other app. I got the code working, but then it mysteriosly stopped working. I'm getting malformed JSON error, even though JSON validator says my file is fine. When i try other JSON file it works fine.
Here's the JSON:
[{
"value1": "Example",
"value2": "Other example"
}]
And here's the PHP (don't mind the Finnish variable names):
$url = "velat.json";
$velat_json = file_get_contents($url);
$velatarray = array();
$velat = json_decode($velat_json);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
foreach($velat as $velka){
$velatarray[] = $velka;
}
header("Access-Control-Allow-Origin: *"); //CORS
header("Content-type: application/json");
print json_encode($velatarray, JSON_PRETTY_PRINT);
What's really weird is that it USED to work. I added feature that allowed me to add new items to JSON file via angular app and even that worked. Then i deleted the added item manually and tried encoding it in utf-8 and suddenly it stopped working, even after i undid all changes and reversed it back to bare bones. How is this happening?
Edit: fixed, BOM was causing the issue
I'm trying to use the V2.2 of StackExchange api with PHP. I'm using the Symfony project with Kriswallsmith's buzz library.
The problem comes when I try to print the content of response of HTTP request and its encode. I have already read lots of question related with this problem in StackOverflow but the problem still exists.
This is a portion of code where I show the problem:
echo "The url: ";
var_dump($url);
var_dump($response);
$content = $response->getContent();
echo "Json decode's content: ";
var_dump(json_decode($content, true));
echo "The error is";
switch(json_last_error()) {
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Invalid or malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
}
die();
This returns the following:
If you paste the
https://api.stackexchange.com/2.2/answers?site=stackoverflow&sort=activity&
in the browser, it returns a valid JSON.
It occurs to me that for some reason the content is not ungzipped:
$ curl https://api.stackexchange.com/2.2/answers
�VJ-*�/��LQ�210ЁrsS���S����3KR2��R
K3�RS�`J�sA�I�)��E#NIj�R-g��PP
$ curl https://api.stackexchange.com/2.2/answers | gzip -d
{"error_id":400,"error_message":"site is required","error_name":"bad_parameter"}
You should be able to use PHP's gzuncompress function or dig Buzz a bit.
This is a json api : https://jobs.github.com/positions.json?description=java&page=1
I want get the data from this url.
<?php
$url = file_get_contents('https://jobs.github.com/positions.json?description=java&page=1');
var_dump(json_decode($url,true)); ?>
this code return null
I also check the url in json validator: http://jsonformatter.curiousconcept.com/ the json is valid but i con't able get the data from this url please help me...
Try this script to determine what the problem is. If there is no JSON module installed (see #julian comment), you can try to use PHP implementations of JSON like this: http://pear.php.net/pepr/pepr-proposal-show.php?id=198
if (! extension_loaded('json')) {
echo 'Module JSON not available!';
exit();
}
$url = file_get_contents('https://jobs.github.com/positions.json?description=java&page=1');
$data = json_decode($url,true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
My web host is running PHP 5.3, but for some reason I cannot use Json_decode(). Why is that? How can I make it work? Are there any alternatives to Json_decode()?
I am using it like this:
$data= json_decode($_POST['moment']);
var_dump($_POST['moment']);
foreach($data as $item) {
echo $item;
And it outputs this:
string(22) "[\"36\",\"37\",\"38\"]"
Warning: Invalid argument supplied for foreach() on line 23
By doing the var_dump() I see the string is created, but I cannot get json_decode to work, to create the array $data
Thanks
json_decode returns NULL when the string you ask it to decode is not valid. You can use json_last_error to diagnose the issue.
When you are going to loop an array like that, you should make sure the value is actually an array.
$data= json_decode($_POST['moment'], true);
if (!is_array($data)) {
echo json_error_string(json_last_error());
} else {
foreach($data as $item) {
echo $item;
}
}
Based on code from the manual:
function json_error_string ($json_error_code) {
switch ($json_error_code) {
case JSON_ERROR_NONE:
return ' - No errors';
break;
case JSON_ERROR_DEPTH:
return ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
return ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
return ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
return ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
return ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
return ' - Unknown error';
break;
}
}
Finally, that you aren't getting any error messages indicates you either have error_reporting off or display_errors off. You need to enable all error reporting with error_reporting(E_ALL & E_STRICT); ini_set('display_errors', '1');. Remove that from production code, but while you're actively working, you need to be seeing all the information possible about the code you are creating.
Documentation
json_decode - http://php.net/manual/en/function.json-decode.php
json_last_error - http://php.net/manual/en/function.json-last-error.php
is_array - http://php.net/manual/en/function.is-array.php
Solved it using stripslashes():
$objJs = json_decode(stripslashes($_POST['obj']));