0

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?

7
  • What is var_dump($data)? Commented May 30, 2013 at 5:40
  • 2
    try calling echo json_last_error_msg () after your json_decode. Commented May 30, 2013 at 5:42
  • $input is received from a HTTP POST, it's shown in #Output line Commented May 30, 2013 at 5:42
  • @kevinamadeus: $var_dump give null. Commented May 30, 2013 at 5:51
  • 1
    @Suranga It's not the quotes. When you are reading the data from 'php://input' something else is put into $input, that's why json_decode breaks Commented May 30, 2013 at 6:02

1 Answer 1

0

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 ?

Sign up to request clarification or add additional context in comments.

1 Comment

It was ok in the file. But when I check the var_dump($input) it was like software+json string. The additional software term was sent by the client. It was removed and now it's working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.