Home > OS >  Cant access JSON data with PHP
Cant access JSON data with PHP

Time:10-21

im trying to access the ID and SENT from this JSON but is not working for me.

UPDATED

$json = '{
 "response": {
  "sent": true,
  "message": "Sent to 57304",
  "id": "gBEGVzBChXFYAgmcOrfFpGem8qw"
 }
}';

json_decode($json);

$id=$json->id;
$sent=$json->sent;

echo "</br> id:".$id."</br>";
echo "</br> sent:".$sent."</br>";

CodePudding user response:

Use the php json_decode() function. Like this:

$json = '{
   "response": {
   "sent": true,
   "message": "Sent to 57304",
   "id": "gBEGVzBChXFYAgmcOrfFpGem8qw"
   }
}';

$json = json_decode($json, true);
$json = (object) $json['response'];
echo $json->sent;  // output: 1
echo $json->id;    // output: "gBEGVzBChXFYAgmcOrfFpGem8qw"

1 is the equivalent for a boolean value of true

CodePudding user response:

It Works,There are two label of JSON object,so you cant access inner object directly. you should assign json_decode($json) into a php object like $obj=json_decode($json); here is the working file

<?php
$json = '{
        "response": {
                    "sent": true,
                    "message": "Sent to 57304",
                    "id": "gBEGVzBChXFYAgmcOrfFpGem8qw"
                    }
        }';
   // convert assign json data into php object
   $obj=json_decode($json);
   //All the inner key can be access throug 'response' object
   $id=$obj->response->id;
   $sent=$obj->response->sent;
   
   
   echo "</br> id:".$id."</br>";
   echo "</br> sent:".$sent."</br>";
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related