简体   繁体   中英

Get single field from PHP JSON response

I have an api to get vehicle data by registration mark.

The JSON result is showing a long list of all fields. I am wanting to just get one or two fields. For example Make and Model

$curl = curl_init();
$ApiKey = "xxxx-xxxx-xxxx-xxx";

$url = "https://uk1.ukvehicledata.co.uk/api/datapackage/%s?v=2&api_nullitems=1&key_vrm=%s&auth_apikey=%s";
$url = sprintf($url, "VehicleData", "AK18OKJ", $ApiKey); 

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_SSL_VERIFYPEER => false,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET"
));

$response = curl_exec($curl);

$error = curl_error($curl);

curl_close($curl);


    echo"<pre>";  
  var_dump(json_decode($response, true)); 
  echo"</pre>"; 

Here is the raw JSON i get back

{
  "BillingAccount": {
    "AccountType": "Trial",
    "AccountBalance": 999.99,
    "TransactionCost": 999.99,
    "ExtraInformation": {}
  },
  "Request": {
    "RequestGuid": "a70b0a56-2dfb-4a8e-887f-ad5928be7908",
    "PackageId": "f66badad-d49d-4489-8322-8a97bb650596",
    "PackageVersion": 2,
    "ResponseVersion": 2,
    "DataKeys": {
      "Vrm": "AK18OKJ"
    }
  },
  "Response": {
    "StatusCode": "Success",
    "StatusMessage": "Success",
    "StatusInformation": {
      "Lookup": {
        "StatusCode": "Success",
        "StatusMessage": "Success",
        "AdviceTextList": []
      }
    },
    "DataItems": {
      "TechnicalDetails": {
        "Dimensions": {
          "UnladenWeight": 1715,
          "RigidArtic": "RIGID",
          "BodyShape": "NA",
          "PayloadVolume": null,
          "PayloadWeight": null,
          "Height": 1404,
          "NumberOfDoors": 5,
          "NumberOfSeats": 5,
          "KerbWeight": 1715,
          "GrossTrainWeight": null,
          "FuelTankCapacity": 58,
          "LoadLength": null,
          "DataVersionNumber": null,
          "WheelBase": 2826,
          "CarLength": 4781,
          "Width": 1866,
          "NumberOfAxles": 2,
          "GrossVehicleWeight": 2305,
          "GrossCombinedWeight": null
        },
        "Safety": {
          "EuroNcap": {
            "Child": null,
            "Adult": null,
            "Pedestrian": null
          }
        },
        "General": {
          "Engine": {
            "FuelCatalyst": "C",
            "Stroke": 86,
            "PrimaryFuelFlag": "Y",
            "ValvesPerCylinder": 4,
            "Aspiration": "TURBO",
            "FuelSystem": "P DI Turbo Cat Euro 6",
            "NumberOfCylinders": 6,
            "CylinderArrangement": "V",
            "ValveGear": "DOHC",
            "Location": "FRONT",
            "Description": null,
            "Bore": 84,
            "Make": "AUDI",
            "FuelDelivery": "Direct Injection"
          },
          "PowerDelivery": "NORMAL",
          "TypeApprovalCategory": "M1",
          "ElectricVehicleBattery": {
            "Capacity": null,
            "ChargePort": null,
            "ChargeTime": null,
            "Type": null
          },
          "SeriesDescription": "B9",
          "DriverPosition": "R",
          "DrivingAxle": "4X4",
          "DataVersionNumber": null,
          "EuroStatus": "6",
          "IsLimitedEdition": false
        },
        "Performance": {
          "Torque": {
            "FtLb": 442.8,
            "Nm": 600,
            "Rpm": 1900
          },
          "NoiseLevel": null,
          "DataVersionNumber": null,
          "Power": {
            "Bhp": 443.9,
            "Rpm": 5700,
            "Kw": 331
          },
          "MaxSpeed": {
            "Kph": 250,
            "Mph": 155
          },
          "Co2": 199,
          "Particles": null,
          "Acceleration": {
            "Mph": 4,
            "Kph": null,
            "ZeroTo60Mph": 4,
            "ZeroTo100Kph": null
          }
        },
        "Consumption": {
          "ExtraUrban": {
            "Lkm": 7.2,
            "Mpg": 39.2
          },
          "UrbanCold": {
            "Lkm": 11.5,
            "Mpg": 24.6
          },
          "Combined": {
            "Lkm": 8.8,
            "Mpg": 32.1
          }
        }
      },
      "ClassificationDetails": {
        "Smmt": {
          "Make": "AUDI",
          "Mvris": {
            "ModelCode": "HQZ",
            "MakeCode": "M3"
          },
          "Trim": "RS 4 TFSI QUATTRO",
          "Range": "A4"
        },
        "Dvla": {
          "Model": "RS 4 TFSI QUATTRO AUTO",
          "Make": "AUDI"
        }
      },
      "VehicleStatus": {
        "MotVed": {
          "VedRate": {
            "FirstYear": {
              "SixMonth": null,
              "TwelveMonth": 1280
            },
            "PremiumVehicle": {
              "YearTwoToSix": {
                "TwelveMonth": 465,
                "SixMonth": 255.75
              }
            },
            "Standard": {
              "SixMonth": 79.75,
              "TwelveMonth": 145
            }
          },
          "VedCo2Emissions": 199,
          "MotDue": null,
          "VedBand": null,
          "VedCo2Band": "K",
          "TaxDue": null,
          "Message": null,
          "VehicleStatus": null
        }
      },
      "VehicleHistory": {
        "V5CCertificateCount": 0,
        "PlateChangeCount": 0,
        "NumberOfPreviousKeepers": 0,
        "V5CCertificateList": [],
        "KeeperChangesCount": 0,
        "VicCount": 0,
        "ColourChangeCount": null,
        "ColourChangeList": null,
        "KeeperChangesList": null,
        "PlateChangeList": [],
        "VicList": null
      },
      "VehicleRegistration": {
        "DateOfLastUpdate": "2020-01-17T20:31:43",
        "Colour": "GREY",
        "VehicleClass": "Car",
        "CertificateOfDestructionIssued": false,
        "EngineNumber": "DECA008416",
        "EngineCapacity": "2894",
        "TransmissionCode": null,
        "Exported": false,
        "YearOfManufacture": "2018",
        "WheelPlan": "2 AXLE RIGID BODY",
        "DateExported": null,
        "Scrapped": false,
        "Transmission": null,
        "DateFirstRegisteredUk": "2018-06-16T00:00:00",
        "Model": "RS 4 TFSI QUATTRO AUTO",
        "GearCount": 8,
        "ImportNonEu": false,
        "PreviousVrmGb": null,
        "GrossWeight": 2305,
        "DoorPlanLiteral": "ESTATE",
        "MvrisModelCode": "HQZ",
        "Vin": "Contact your account manager for access to the full VIN value.",
        "Vrm": "AK18OKJ",
        "DateFirstRegistered": "2018-06-16T00:00:00",
        "DateScrapped": null,
        "DoorPlan": "06",
        "YearMonthFirstRegistered": "2018-06",
        "VinLast5": "02977",
        "VehicleUsedBeforeFirstRegistration": false,
        "MaxPermissibleMass": 2305,
        "Make": "AUDI",
        "MakeModel": "AUDI RS 4 TFSI QUATTRO AUTO",
        "TransmissionType": "Semi-Automatic",
        "SeatingCapacity": 5,
        "FuelType": "PETROL",
        "Co2Emissions": 200,
        "Imported": false,
        "MvrisMakeCode": "M3",
        "PreviousVrmNi": null,
        "VinConfirmationFlag": null
      },
      "SmmtDetails": {
        "Range": "A4",
        "FuelType": "PETROL",
        "EngineCapacity": "2894",
        "MarketSectorCode": "AA",
        "CountryOfOrigin": "GERMANY",
        "ModelCode": "459",
        "ModelVariant": "RS 4 TFSI QUATTRO",
        "DataVersionNumber": null,
        "NumberOfGears": 8,
        "NominalEngineCapacity": 3,
        "MarqueCode": "MT",
        "Transmission": "AUTOMATIC",
        "BodyStyle": "ESTATE",
        "VisibilityDate": "02/10/2017",
        "SysSetupDate": "02/10/2017",
        "Marque": "AUDI",
        "CabType": "NA",
        "TerminateDate": null,
        "Series": "B9",
        "NumberOfDoors": 5,
        "DriveType": "4X4"
      }
    }
  }
}

First you have to decode your JSON-String into an associative array. Here you can read about it: https://www.w3schools.com/php/php_arrays_associative.asp

$assoc_array = json_decode($response, true); // set second parameter to true to get an associative array as return value

Then you can access it this way:

echo $assoc_array['Response']['DataItems']['ClassificationDetails']['Smmt']['Make'];
// returns AUDI

This code displays the array readable for you and can help you finding the right keys:

echo '<pre>';
print_r( $assoc_array );
echo '</pre>';
$response  =  '{"BillingAccount":{"AccountType":"Trial","AccountBalance":999.99,"TransactionCost":999.99,"ExtraInformation":{}},"Request":{"RequestGuid":"a70b0a56-2dfb-4a8e-887f-ad5928be7908","PackageId":"f66badad-d49d-4489-8322-8a97bb650596","PackageVersion":2,"ResponseVersion":2,"DataKeys":{"Vrm":"AK18OKJ"}},"Response":{"StatusCode":"Success","StatusMessage":"Success","StatusInformation":{"Lookup":{"StatusCode":"Success","StatusMessage":"Success","AdviceTextList":[]}},"DataItems":{"TechnicalDetails":{"Dimensions":{"UnladenWeight":1715.0,"RigidArtic":"RIGID","BodyShape":"NA","PayloadVolume":null,"PayloadWeight":null,"Height":1404.0,"NumberOfDoors":5,"NumberOfSeats":5,"KerbWeight":1715.0,"GrossTrainWeight":null,"FuelTankCapacity":58.00,"LoadLength":null,"DataVersionNumber":null,"WheelBase":2826.0,"CarLength":4781.0,"Width":1866.0,"NumberOfAxles":2,"GrossVehicleWeight":2305.0,"GrossCombinedWeight":null},"Safety":{"EuroNcap":{"Child":null,"Adult":null,"Pedestrian":null}},"General":{"Engine":{"FuelCatalyst":"C","Stroke":86.0,"PrimaryFuelFlag":"Y","ValvesPerCylinder":4,"Aspiration":"TURBO","FuelSystem":"P DI Turbo Cat Euro 6","NumberOfCylinders":6,"CylinderArrangement":"V","ValveGear":"DOHC","Location":"FRONT","Description":null,"Bore":84.0,"Make":"AUDI","FuelDelivery":"Direct Injection"},"PowerDelivery":"NORMAL","TypeApprovalCategory":"M1","ElectricVehicleBattery":{"Capacity":null,"ChargePort":null,"ChargeTime":null,"Type":null},"SeriesDescription":"B9","DriverPosition":"R","DrivingAxle":"4X4","DataVersionNumber":null,"EuroStatus":"6","IsLimitedEdition":false},"Performance":{"Torque":{"FtLb":442.80,"Nm":600.0,"Rpm":1900.0},"NoiseLevel":null,"DataVersionNumber":null,"Power":{"Bhp":443.90,"Rpm":5700.0,"Kw":331.00},"MaxSpeed":{"Kph":250.0,"Mph":155.0},"Co2":199.0,"Particles":null,"Acceleration":{"Mph":4.00,"Kph":null,"ZeroTo60Mph":4.00,"ZeroTo100Kph":null}},"Consumption":{"ExtraUrban":{"Lkm":7.20,"Mpg":39.20},"UrbanCold":{"Lkm":11.50,"Mpg":24.60},"Combined":{"Lkm":8.80,"Mpg":32.10}}},"ClassificationDetails":{"Smmt":{"Make":"AUDI","Mvris":{"ModelCode":"HQZ","MakeCode":"M3"},"Trim":"RS 4 TFSI QUATTRO","Range":"A4"},"Dvla":{"Model":"RS 4 TFSI QUATTRO AUTO","Make":"AUDI"}},"VehicleStatus":{"MotVed":{"VedRate":{"FirstYear":{"SixMonth":null,"TwelveMonth":1280.0},"PremiumVehicle":{"YearTwoToSix":{"TwelveMonth":465.0,"SixMonth":255.75}},"Standard":{"SixMonth":79.75,"TwelveMonth":145.0}},"VedCo2Emissions":199.0,"MotDue":null,"VedBand":null,"VedCo2Band":"K","TaxDue":null,"Message":null,"VehicleStatus":null}},"VehicleHistory":{"V5CCertificateCount":0,"PlateChangeCount":0,"NumberOfPreviousKeepers":0,"V5CCertificateList":[],"KeeperChangesCount":0,"VicCount":0,"ColourChangeCount":null,"ColourChangeList":null,"KeeperChangesList":null,"PlateChangeList":[],"VicList":null},"VehicleRegistration":{"DateOfLastUpdate":"2020-01-17T20:31:43","Colour":"GREY","VehicleClass":"Car","CertificateOfDestructionIssued":false,"EngineNumber":"DECA008416","EngineCapacity":"2894","TransmissionCode":null,"Exported":false,"YearOfManufacture":"2018","WheelPlan":"2 AXLE RIGID BODY","DateExported":null,"Scrapped":false,"Transmission":null,"DateFirstRegisteredUk":"2018-06-16T00:00:00","Model":"RS 4 TFSI QUATTRO AUTO","GearCount":8,"ImportNonEu":false,"PreviousVrmGb":null,"GrossWeight":2305.0,"DoorPlanLiteral":"ESTATE","MvrisModelCode":"HQZ","Vin":"Contact your account manager for access to the full VIN value.","Vrm":"AK18OKJ","DateFirstRegistered":"2018-06-16T00:00:00","DateScrapped":null,"DoorPlan":"06","YearMonthFirstRegistered":"2018-06","VinLast5":"02977","VehicleUsedBeforeFirstRegistration":false,"MaxPermissibleMass":2305.0,"Make":"AUDI","MakeModel":"AUDI RS 4 TFSI QUATTRO AUTO","TransmissionType":"Semi-Automatic","SeatingCapacity":5,"FuelType":"PETROL","Co2Emissions":200.0,"Imported":false,"MvrisMakeCode":"M3","PreviousVrmNi":null,"VinConfirmationFlag":null},"SmmtDetails":{"Range":"A4","FuelType":"PETROL","EngineCapacity":"2894","MarketSectorCode":"AA","CountryOfOrigin":"GERMANY","ModelCode":"459","ModelVariant":"RS 4 TFSI QUATTRO","DataVersionNumber":null,"NumberOfGears":8,"NominalEngineCapacity":3.00,"MarqueCode":"MT","Transmission":"AUTOMATIC","BodyStyle":"ESTATE","VisibilityDate":"02/10/2017","SysSetupDate":"02/10/2017","Marque":"AUDI","CabType":"NA","TerminateDate":null,"Series":"B9","NumberOfDoors":5,"DriveType":"4X4"}}}}';


// first decode the json into an array
$data = json_decode($response, true);
// next, grab the Dvla data from that array if it exists to make the rest simpler
$dvla = isset($data['Response']['DataItems']['ClassificationDetails']['Dvla']) ? $data['Response']['DataItems']['ClassificationDetails']['Dvla'] : [];

// now, grab the make and model from that Dvla data if it exists
$make  = isset($dvla['Make']) ? $dvla['Make'] : null;
$model = isset($dvla['Model']) ? $dvla['Model'] : null;

echo "Make: $make, Model: $model";

Prints Make: AUDI, Model: RS 4 TFSI QUATTRO AUTO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM