Thursday, January 6, 2022

[SOLVED] Extract data from JSON with PHP?

Issue

i want to take data of username(david) from this Json , I saw the similar question i try more than 100 times but i can not , I need exact answer if it's possible. thanks in advance

{
    "related_assets": [],
  "orders": [],
  "auctions": [],
  "supports_wyvern": true,
  "top_ownerships": [
    {
      "owner": {
        "user": {
          "username": "david"
        },
        "",
        "address": "",
        "config": ""
      },
      "quantity": "1"
    }
  ],
  "ownership": null,
  "highest_buyer_commitment": null
}

and i coded as below :

<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
    //the second parameter turns the objects into an array
    $decodedData = json_encode($response, true);
    $owner = $decodedData['top_ownerships'][0]['owner'];
    $username = $owner['user']['username'];
    echo $username;


}

the output is " please help thanks


Solution

your code is completely current! and it works like charm!

but you made a very ambiguous mistake in your JSON code

you're using this ” instead of " (double quotes) there "david” <----

they exactly look the same!

and also you missed {} in the beginning and end of your JSON code

checkout your json code here it's the best tool for this

<?php

$code = '{
    "top_ownerships": [{
        "owner": {
            "user": {
                "username": "david"
            },
            "profile_img_url": "",
            "address": "",
            "config": ""
        },
        "quantity": "1"
    }]
}';

  $decodedData = json_decode($code, true);

  $owner = $decodedData['top_ownerships'][0]['owner'];
  $username = $owner['user']['username'];
  echo $username;

?>


Answered By - CyC0der