Home > database >  Filter JSON response in PHP
Filter JSON response in PHP

Time:01-17

I have a API and need to validate the input, then if it's valid I print some objects of the JSON response. What I have is:

  <?php
                $headers = [
                    "User-Agent: Test API",
                    "token: *my-token*"
                ];
                
                $accountid = $_POST['accountid'];
                $url = "https://my api url/$accountid";           
                
                $ch = curl_init($url);

                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                $result = curl_exec($ch);
                curl_close($ch);
                
                $data = json_decode($result, true);

                if (preg_match('/404/',$result)){
                    echo "AccountID invalid.";
                }
                else {
                    echo "AccountID valid:\n";
                } 
                ?>

And the return is right, I'm receiving my api response. My api returns this:

{
    "status": "ACTIVE",
    "id": "DEFAULT",
    "add": [{
        "key": "state",
        "value": "New York"
    }, {
        "key": "city",
        "value": "New York"
    }],
    "created": "2023-01-16",
    "modified": "2023-01-16",
    "_id": "50000000"
}

I'm trying to filter this JSON response, for example, if it's valid, I want it to show me just the "status", "modified" and _"id" from my JSON. I'm very new to PHP, still learning. Could anybody help me?

I've tried to use foreach inside my else like this:

               $data = json_decode($result, true);

                if (preg_match('/404/',$result)){
                    echo "AccountID invalid.";
                }
                else {
                    echo "AccountID valid:\n";
                    foreach ($data as $values){
                     echo $values["status"],
                     echo $values["modified"],
                     echo $values["_id"];

                } 

the error is: Uncaught TypeError: Cannot access offset of type string on string.

CodePudding user response:

You need to check if the status is ACTIVE, then access the json data.

<?php 
   if( $result === false){
     echo "Error Request";
   }else{
     $data = json_decode($result);
     if($data->status == "ACTIVE"){
       echo $data->_id;
        echo $data-> modified
     }else{
      echo "Invalid Data";
     }
  }
  • Related