MrTechie
MrTechie

Reputation: 1847

json_decode() in PHP not showing true or false statements

I have a response coming back that is JSON encoded, but when I decode it I lose the true/false attributes after using $var = json_decode($response);.

Here’s an example:

{
  "domain": "my.domain.com",
  "created_at": "2014-11-15 00:26:53.74059",
  "valid_mx": true
}

I’ve even tried:

$var = json_decode($response, true);

But it still seems to drop the true/false. How can I properly pull the true/false from the response? What am I missing?

Upvotes: 11

Views: 10698

Answers (4)

Shree Ram Sharma
Shree Ram Sharma

Reputation: 51

Just put the true in a quote and it will be working fine.

<?php
$response = '{
                "domain": "my.domain.com",
                "created_at": "2014-11-15 00:26:53.74059",
                "valid_mx": "true"
      }';

$var = json_decode($response, true); 
echo $var["valid_mx"]; // it will print true   
?>

Upvotes: -2

Rizier123
Rizier123

Reputation: 59681

This should work for you:

(With this you have the JSON string as an array)

<?php

    $response = '{
                "domain": "my.domain.com",
                "created_at": "2014-11-15 00:26:53.74059",
                "valid_mx": true
            }';

    $var = json_decode($response, true);    

    if($var["valid_mx"] === TRUE)
        echo "true";
    else
        echo "false";

?>

Output:

yes

If you want an object just change this line:

$var = json_decode($response, true);

to this:

$var = json_decode($response);

And then you can access it with this line:

if($var->valid_mx === TRUE)

Upvotes: 6

rjdown
rjdown

Reputation: 9227

Your problem is with print_r, not json_decode.

print_r does not show true / false for true / false. Instead, it shows 1 / (blank).

You can use var_dump($var); or var_export($var); instead which will show you the correct values.

Upvotes: 12

mcdonaldjosh
mcdonaldjosh

Reputation: 119

This works for me:

if(json_decode($response)->valid_max){
   //your stuff
}

Upvotes: 1

Related Questions