以下是我要解析的JSON:
{"results":[{"id":471033736,"url":"https://site.com/471033736.json","name":"Joe User","email":"xxxxx@someplace.com","created_at":"2013-09-16T16:34:23Z","updated_at":"2013-09-16T16:34:23Z","time_zone":"America/Los_Angeles","phone":null,"photo":null,"locale_id":null,"locale":"en-US","organization_id":20477117,"role":"end-user","verified":false,"split_testing_group_names":[],"external_id":null,"tags":[],"alias":null,"active":true,"shared":false,"shared_agent":false,"last_login_at":null,"signature":null,"details":null,"notes":null,"custom_role_id":null,"moderator":false,"ticket_restriction":"requested","only_private_comments":false,"restricted_agent":true,"suspended":false,"user_fields":{},"result_type":"user"}]}
问题是当我尝试通过以下方法在PHP中的curlWrap()方法中解析此JSON时:
$data=curlWrap("/api/v2/search.json?page="."$page_count"."&query=type:user", null, "GET"))
foreach ($data as $user_data){
echo "This is: {$user_data}";
echo "\n";
}
打印以下内容(似乎是对象的顶级):
这是:数组
这是:
这是:https://example.com/v2/search.json?page=2&query=type%3Auser
这是:
这是:605
如果我查看原始(浏览器)端点中的JSON,则显示:
{
"results": [ … ],
"facets": null,
"next_page": "https://example.com/api/v2/search.json?page=2&query=type%3Auser",
"previous_page": null,
"count": 605
}
如何使用PHP访问“结果”数据?
@ ed-cotrell这是var_dump($ data)的输出:
array(5) { ["results"]=> array(100) { [0]=> array(33) { ["id"]=> int(471033736) ["url"]=> string(61) "example/api/v2/users/471033736.json"; ["name"]=> string(13) "xxxx" ["result_type"]=> string(4) "user" } [1]=> . . } } ["facets"]=> NULL ["next_page"]=> string(77) "example/api/v2/search.json?page=2&query=type%3Auser"; ["previous_page"]=> NULL ["count"]=> int(605) }
@AbraCadaver - 这是print_r($ data)的输出:
Array
(
[results] => Array
(
[0] => Array
(
[id] => 471033736
[url] => https://example.com/api/v2/users/471033736.json
[name] => Joe User
[email] => Joeuser@nowhere.comcom
[created_at] => 2013-09-16T16:34:23Z
[updated_at] => 2013-09-16T16:34:23Z
[time_zone] => America/Los_Angeles
(
)
[result_type] => user
)
)
[facets] =>
[next_page] => https://site.com/api/v2/search.json?page=2&query=type%3Auser
[previous_page] =>
[count] => 605
)
答案 0 :(得分:2)
您可以使用PHP的内置json_decode
函数:
$data=curlWrap(...);
$data = json_decode($data);
var_dump($data);
应该显示JSON对象的内部。 JSON_DECODE函数将您的JSON字符串转换为标准PHP变量。
答案 1 :(得分:2)
如果你为curlWrap函数输入函数定义会很有帮助。但说实话,我甚至不再使用cURL了。不是file_get_contents的出现,而是能够从外部源(例如URL)读取。
您甚至可以发送自定义标题,操作类型(POST,PUT,GET等)以及您在cURL中可以执行的所有操作。它更容易使用。
这样做:
<?php
$url = 'http://api.mydomain.com/my-api-path/some_method/some_id';
$rawText = file_get_contents($url);
$responseObject = json_decode($rawText);
print_r($responseObject);
?>
答案 2 :(得分:0)
$data
只包含一个字符串。你需要解析它:
$data = json_decode($data);
foreach ($data as $user_data) { // etc.
答案 3 :(得分:0)
显然curlWrap()
已经解码了JSON。问题是$data
是一个对象,results
是一个对象属性,是一个数组。您需要以数组形式访问$data->results
:
foreach($data->results as $result) {
echo $result;
}
null
的对象属性不是字符串,它们实际上是null
值,因此您不会看到它们。