简体   繁体   中英

PHP json_decode does not work

I am trying the following code to receive JSON . However the decode does not give a result. It works for a copy of the same string with escape slashes.

<?php
$input = file_get_contents('php://input');
logToFile("post.txt",$input);
#Output: {"id":"id1","model":"model1","version":"v1","software":["s1","s2","s3"]}

$data = json_decode($input,true);
logToFile("post.txt",$data['version']);
#Output:Empty result

### Works
$data1 = json_decode("{\"id\":\"id1\",\"model\":\"model1\",\"version\":\"v1\",\"software\":[\"s1\",\"s2\",\"s3\"]}",true);
logToFile("post.txt",$data1['version']);
#Output:v1

function logToFile($filename,$msg)
{
  $fd=fopen($filename,"a");
  $str="[".date("Y/m/d h:i:s")."]".$msg;
  fwrite($fd,$str."\n");
  fclose($fd);
}
?>

I am using PHP 5.4. So it's not a problem in magic quotes. Any help?

I don't think the problem is with the json_decode.

$input = '{"id":"id1","model":"model1","version":"v1","software":["s1","s2","s3"]}';
$data = json_decode($input,true);
echo $data['version'];

Works fine.

So if you go:

echo "<pre>";
print_r( $input );
echo "</pre>";

After you get the $input from the file. Does it appear OK ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM