json_decode error - php

I'm having issue working with json_decode() in PHP. Im using the json2.js library to convert a JSON to string. Then post it to PHP. That part seems fine.
Here is my PHP function :
public function SaveUser($json){
$json2 = json_decode($json,true);
print 'Intrant : <br />'.$json.'<br />';
print '<pre>VAR DUMP:<br />';
var_dump($json2);
print '</pre>';
// Do some things
}
The following returns the following :
Intrant :
{"user_id":"14","prenom":"prenom","nom":"nom","profil_heures_fixe":"0","nb_heures_fixe":"","is_userliste":"1","is_paye":"1","username":"username","password":"","telephone":"111-111-1111","cellulaire":"111-111-1111","extension":"30","courriel":"user#server.com","date_embauche":"2017-07-02","machine":"","profil_id":"4","status_id":"1","coordonnees":"","urgence":""}
VAR DUMP:
NULL

The follow works just fine for me:
<?php
function SaveUser($json){
$json2 = json_decode($json,true);
print 'Intrant : <br />'.$json.'<br />';
print '<pre>VAR DUMP:<br />';
var_dump($json2);
print '</pre>';
// Do some things
}
$t = '{"user_id":"14","prenom":"prenom","nom":"nom","profil_heures_fixe":"0","nb_heures_fixe":"","is_userliste":"1","is_paye":"1","username":"username","password":"","telephone":"111-111-1111","cellulaire":"111-111-1111","extension":"30","courriel":"user#server.com","date_embauche":"2017-07-02","machine":"","profil_id":"4","status_id":"1","coordonnees":"","urgence":""}';
SaveUser($t);
If that doesn't work for you (as a PHP script on its own), then it's possible you don't have PHP's json extension installed. Check using either "php -m | grep json" or function_exists("json_decode").

dont know what your doing ..
but works here perfectly
http://pastebin.com/DzSs8mNd

Your json string, as displayed by the browser, parses correctly. I think a few of us have seen that. But, what the browser displays and what is really there are often very different things. For example, you might have a whitespace character hidden in the wrong spot. Try moving the <pre> and see what happens:
print '<pre>Intrant : <br />'.$json.'<br />';
print 'VAR DUMP:<br />';
var_dump($json2);
print '</pre>';

Thanks Marc B,
Since our server is using the charset ISO-8859-1 the json_decode function does not work.
$json2 = json_decode(utf8_encode($json),true);
Thanks all

Related

Print json in pretty format using php code

I have array like below.
$resultArr = array();
$resultArr['status code'] = 200;
$resultArr['result'] = "Success";
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
return $json;
This is giving result like below
"{\n \"status code\": \"200\",\n \"result\": \"Success\",\n}"
without Pretty_print the result is like below
"{\"status code\":\"200\",\"result\":\"Success\"}"
I want response to be like this
{
"status code": 200,
"result": "Success"
}
Is something like this can be done pls, I am using PHP, Running the request in postman and the response are mentioned above
Note: I need to avoid using echo, because we are using code sniffers in project, so echo is not recommended.
You used JSON_PRETTY_PRINT for beautify output purpose,
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
If you want to use it as response remove that parameter,
$json = json_encode($resultArr);
Above line should work.
First of all, remove the JSON_PRETTY_PRINT flag.
Secondly, your problem is with the backslashes (\). These are escape characters. I don't know how you are printing your json or how you are viewing it.
If I do:
echo $json;
It outputs:
{"status code":200,"result":"Success"}
The backslashes are probably added because you're doing an AJAX request. In order to solve this, you could use jQueries .parseJSON() or add dataType: "json" to your ajax request.
And if you really don't want the backslashes to be added:
$json = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
Update
It might help to output using the following header:
header('Content-Type: application/json');
1. for Output Of API You Can Use Api:
header('Content-Type: application/json');
2. Using JSON_PRETTY_PRINT
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
3. You want To Display In Chrome
https://addons.mozilla.org/en-US/firefox/addon/json-handle/?src=recommended

Form post has "%10" written by user - json_decode() fails with urldecode()

Was so awesome of the customer to type "%10" instead of "10%"
0_o
$PACKAGE_json_decode = json_decode(urldecode(($_POST['textarea']), true);
print_r($PACKAGE_json_decode); // LENGTH 0
foreach($PACKAGE_json_decode as $row){
}
ERROR:
"Message: Invalid argument supplied for foreach()"
How do I urldecode without causing the %10 to take on a different meaning when sent back via AJAX?
And decode seems to produce that square character I cannot paste here... you know ... looks sorta like "[]"
*The string needs to be the same for the client when they get it back - they save it with a % they want it back with a %.
- Any suggestions about replacing it?
The % character is used in URL encoding. Either you remove % from the front end before passing to the server or you deal the same in the server side.
You could encode your request send by Ajax directly, such as below:
$.ajax({
type:'POST',
dataType: 'json',
...
Or like this:
JSON.stringify('%10');
Inside your PHP, just json_decode() now, as below.
$PACKAGE_json_decode = json_decode($_POST['textarea']);
Like this, your %10 will become "%10", et voila!!!
Please use the following code and let me know where is it breacking ?
<?php
$url_encode = urldecode("sampleTextWith%");
echo '<b>Ecoded URL </b>'. $url_encode."<br>";
$obj = new StdClass();
$obj->text = $url_encode;
$encoded_json = json_encode($obj);
echo '<b>Encoded JSON </b>'. $encoded_json."<br>";
$decoded_json = json_decode($encoded_json);
echo "<b>Decoded JSON </b>";
print_r($decoded_json);
echo "<br>";
foreach($decoded_json as $row){
echo "<b>Row Value : </b>". $row."<br>";
}
?>

Modified variable variables

$m = 'this_is_m';
$this_is_m = 'this_is_m_not_full :(';
$this_is_m_full = 'this_is_m_FULL!! :D';
print ${$m};
(Hi first :P) Outputs:
this_is_m_not full :(
Any idea how to output this_is_m_FULL!! :D using $m??
What I've already tried:
print $"{$m}_full";
print $'{$m}_full';
print $'$m_full';
print ${$m}_full';
None worked... Thanks in advance,,
The solution would be:
print ${$m . '_full'};
But that feels very hackish.
To get your desired output, you need to do the following:
print ${$m . "_full"};
The following should work:
print ${$m.'_full'};
This is because the string inside the braces will get evaluated first, becoming
print ${'this_is_m' . '_full'}
-> print ${'this_is_m_full'}
-> print $this_is_m_full
Take a look at this manual page if you want more information on this.

Displaying PHP variable output

I've noticed that when I try to display the value of a variable with PHP, for example using print_r($array)/var_dump(), etc or even when using the Reflection API, I end up with output that is hard to read because there are no line breaks. Every screen shot I see everywhere else has these things displayed in a sort of tree looking format that is much easier to read. Does anyone know why this is?
It's not a native feature of Php. Try installing X-Debug for a better look and feel of your var_dump.
Try:
echo nl2br($output);
Or try viewing it with the "View source" option of your browser.
Hope this helps
EDIT
OR just use the pre tags, like this:
<?php
function my_print_r($var) {
$output = "";
$output .= "<pre>";
$output .= print_r($var, true);
$output .= "</pre>";
return $output;
}
echo my_print_r(array(1, 2, 3));
?>
If you would view it in a browser you could wrap it inside the <pre> HTML tag like so:
echo "<pre>";
print_r($output);
echo "</pre>\n";
Try adding echo '<pre>'; before printing the variable

issue when outputting an http:// address in a sub-array with json and php

Im trying to achieve an output like this
{"status":"ok","0":{"id":"11","title":"digg","url":"http://www.digg.com"}}
but instead i am getting this
{"status":"ok","0":{"id":"11","title":"digg","url":"http:\/\/www.digg.com"}}
this is the php code im using to generate the json
$links = array('id'=>'11','title'=>'digg','url'=>"http://www.digg.com");
$msg = array('status'=>'ok',$links);
echo json_encode($msg);
any idea what is causing this?
UPDATE
i should have been more clear
if you notice the actual url, its inserting "\" before the "/" in the output. Is this supposed to happen, or is there a way to stop this?
They're both equivalent valid JSON, so it shouldn't matter. The JSON strings:
"http://www.digg.com"
and
"http:\/\/www.digg.com"
both decode to:
"http://www.digg.com"
This is a separate issue, but I would prefer:
$links = array(array('id'=>'11','title'=>'digg','url'=>"http://www.digg.com"));
$msg = array('status'=>'ok', 'links'=>$links);
echo json_encode($msg);
{"status":"ok","links":[{"id":"11","title":"digg","url":"http:\/\/www.digg.com"}]}
This makes more sense to me than having a "0" key, and it extend well if you add more sites:
$links = array(array('id'=>'11','title'=>'digg','url'=>"http://www.digg.com"),
array('id'=>'12','title'=>'reddit','url'=>"http://www.reddit.com"));
$msg = array('status'=>'ok', 'links'=>$links);
echo json_encode($msg);
{"status":"ok","links":[{"id":"11","title":"digg","url":"http:\/\/www.digg.com"},
{"id":"12","title":"reddit","url":"http:\/\/www.reddit.com"}]}
Yes. The JSON specs.

Categories