如何从url返回json对象作为字符串


How to echo json object from url as a string

我使用这个从url:

获取json
$json_string = file_get_contents('https://www.instagram.com/testuser/?__a=1');
$parsed_json = json_decode($json_string, true);
var_dump($parsed_json);

,我得到json响应返回为:

    {"user": 
 {"username": "testuser", "has_blocked_viewer": false, "follows":
 {"count": 94}, "requested_by_viewer": false, "followed_by":
 {"count": 3}, "country_block": null, "has_requested_viewer": false,
               "external_url_linkshimmed": null, "follows_viewer": false,
               "profile_pic_url_hd": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
               "profile_pic_url": "https://scontent-lhr3-1.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
               "is_private": true, "full_name": null, "media":
 {"count": 0, "page_info":
 {"has_previous_page": false, "start_cursor": null, 
  "end_cursor": null, "has_next_page": false},
  "nodes": []},
  "blocked_by_viewer": false,
  "followed_by_viewer": false, "is_verified": false,
  "id": "3409891", "biography": null, "external_url": null}
}

如何将"profile_pic_url_hd"作为字符串返回?

使用json_decodetrue作为第二个参数,您可以得到一个关联数组,而不能使用printecho数组。试试var_dumpprint_r:

$json_string = file_get_contents('https://www.instagram.com/username/?__a=1');
$parsed_json = json_decode($json_string, true);
print_r($parsed_json);
var_dump($parsed_json);

确保检查错误/异常。在下面我假设'user'和'profile_pic_url'存在于返回的json响应中(返回的json响应是哈希的哈希)。

<?php
$json_string = file_get_contents('https://www.instagram.com/testuser/?__a=1');
$parsed_json = json_decode($json_string, true);
print_r($parsed_json{'user'}{'profile_pic_url'});
?>

反应:

https://scontent-frt3-1.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg