Search code examples
phparraysjsonstringjmespath

How to get particular data from json url


I have following Json Data in php url File name : house.php

{
"Error": "",
"ErrorCode": 0,
"Guid": "",
"Id": 0,
"Success": true,
"Value": [
{
"MAIN": 225,
"PHASE": 219418523,
"G": "7TH Division",
"GI": "2031892",
"DOOR": "8907",
"Gate": {
    "RG": 2,
    "BNS": "4 Window",
    "BS": {
    "SB1": 2
    },
    "TQ": [
    {
        "Key": 1,
        "Value": {
        "T1": 2
        }
    },
    {
        "Key": 2,
        "Value": {}
    }
    ],
    "MR": -1,
    "MS": 600
},
"AA": "81",
"AI": "8745524"
},
{
"MAIN": 300,
"PHASE": 219418523,
"G": "8TH Division",
"GI": "4526892",
"DOOR": "8877",
"GATE": {
    "RG": 2,
    "BNS": "5 Window",
    "BS": {
    "SB1": 2
    },
    "TQ": [
    {
        "Key": 1,
        "Value": {
        "T1": 2
        }
    },
    {
        "Key": 2,
        "Value": {}
    }
    ],
    "MR": -1,
    "MS": 600
},
"AA": "91",
"AI": "8758421"
}]}

I need particular data "G", "G1", "DOOR", "AA", A1" alone to display in my new php file :

completehouse.php in json format what code to give to get particular data.

    <?php
$url="house.php";
$text = file_get_contents($url);
header('Content-Type: application/json');
echo $text;
?>

Currently i am using https://codebeautify.org/online-json-editor manually each time by using transform data query : [*].{G: G, G1: G1, DOOR: DOOR, AA: AA, AI: AI} and getting output

{
      "Error": "",
      "ErrorCode": 0,
      "Guid": "",
      "Id": 0,
      "Success": true,
      "Value": [
{
          "G": "7TH DIVISION",
          "G1": "2031892",
          "DOOR": "8907",
          "AA": "81",
          "AI": "8745524"
        },
{
          "G": "8TH DIVISION",
          "G1": "4526892",
          "DOOR": "8877",
          "AA": "85",
          "AI": "8759544"
        }
      ]
    }

Please someone help me to fix my manual work and save my time.


Solution

  • You can decode your json and then get the exact value of what you want.

    $json = '....';
    $parsed = json_decode($json,true);
    $result = [];
    if($parsed['Success']){ // check if your api json response is true. 
        foreach($parsed['Value'] as $val){
            if($val['AI']> = 9000000){
            $result[] = [
                "G"=> $val['G'],
                "GI"=> $val['GI'],
                "DOOR"=> $val['DOOR'],
                "AA"=> $val['AA'],
                "AI"=> $val['AI']
             ];
             }
             // or what you want.
        }
    }
    
    echo json_encode($result);
    

    see demo