1

If I use the following:

$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
echo $homepage;

The data is displayed as follows:

{"user":{"profile":{"Id":{"Label":"User Id","Value":102210},"User":{"Label":"User Name","Value":"tom"}

I tried the following that I discovered on here in another post but the page remains blank other than User:

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "http://www.website.com/api/v1/members/102210",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache"
    ),
));

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

curl_close($curl);


$response = json_decode($response, true); //because of true, it's in an array
echo 'User: '. $response['User']['User Name'];
2
  • What is the issue ? Can u please format Json and paste it buddy Commented Apr 12, 2016 at 18:26
  • can you print the $response var please ? print_r($response); Commented Apr 12, 2016 at 18:28

1 Answer 1

2

You're misinterpreting the JSON data. There is no User key in the root of the json object and there is no User Name key inside of that either. When you visualize the JSON, this is what it looks like:

json

What you seem to be looking for is:

echo 'User: ' . $response['user']['profile']['User']['Value'];

I'm not sure why you'd switch to cURL if the file_get_content method works for you. You should be able to simply do this:

$homepage = file_get_contents('http://www.website.com/api/v1/members/102210');
$response = json_decode($homepage, true);

echo 'User: ' . $response['user']['profile']['User']['Value'];
Sign up to request clarification or add additional context in comments.

11 Comments

what tool are you using to create the tree diagram? Thanks and good luck to all.
@shellter jsoneditoronline.org, added link to the example in the answer.
@Oldskool it only displays blank page
@William I adjusted the answer a little to show a more complete example. That should show the user and username. If not, your curl request probably throws an error (try adding var_dump($err) to the end of the script to see).
@William On second thought, it looks like file_get_contents works well for you, so why switch to cURL at all? Added an alternative example.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.