使用 PHP 解析特定格式的 JSON 请求

我正在尝试从以下 JSON URL: https://api.fda.gov/drug/label.json?search=levodopa 获取结果部分中的指示和用法部分。

目前为止,我的 PHP 文件中有以下代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$data = curl_exec($ch);

curl_close($ch);

当我打印 $data 时,它会输出整个 JSON。我该如何修改代码以获取指示和用法部分?

由于没有一种方法似乎能工作,这里是当我执行以下代码时的输出开头:

echo $data;

HTTP/1.1 200 Connection established HTTP/1.1 200 OK Access-Control-Allow-Headers: X-Requested-With Access-Control-Allow-Origin: * Age: 0 Cache-Control: public, max-age=60 Content-Security-Policy: default-src 'none' Content-Type: application/json; charset=utf-8 Date: Sun, 21 Feb 2016 19:49:27 GMT ETag: W/"19923-bQuoDHROKCsX/qDsyE4GuA" Server: openresty Vary: Accept-Encoding Vary: Accept-Encoding Vary: Accept-Encoding Via: http/1.1 api-umbrella (ApacheTrafficServer [cSsSfU]) X-Cache: MISS X-Content-Type-Options: nosniff X-Frame-Options: deny X-XSS-Protection: 1; mode=block Content-Length: 104739 Connection: keep-alive { "meta": { "disclaimer": "openFDA 是一个测试版的研究项目,不适用于临床使用。虽然我们尽一切努力确保数据的准确性,但您应该假设所有结果尚未经过验证。", "license": " http://open.fda.gov/license", "last_updated": "2016-02-05", "results": { "skip": 0, "limit": 1, "total": 1400 } }, "results": [ { "effective_time": "20120305", "drug_interactions": [ "DRUG INTERACTIONS Few systemic data have been collected on the metabolism of bupropion following concomitant administration with other drugs or, alternatively, the effect of concomitant administration of bupropion on the metabolism of other drugs. ..... and so on

点赞
用户1207539
用户1207539

你应该能够通过以下方式访问它:

$decoded = json_decode($data, true);

echo $decoded->results[0]->indications_and_usage[0]
2016-02-21 19:37:09
用户5953864
用户5953864

你需要从的 curl 中删除 curl_setopt($ch, CURLOPT_HEADER, 1);。否则,变量 $data 中将包含 HTTP 标头。

完整示例代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);

curl_close($ch);

$result = json_decode($data, true);
$result_string = $result['results'][0]['indications_and_usage'][0];

echo $result_string;
2016-02-21 19:39:43
用户5752737
用户5752737
$json = file_get_contents("https://api.fda.gov/drug/label.json?search=levodopa");
$obj = json_decode($json);
echo "<pre>";
print_r($obj->results[0]->indications_and_usage);
echo "</pre>";

如果你对整个对象进行 print_rvar_dump,你会看到 results 是它的成员之一,一个数组。结果数组的第一个索引是另一个对象,它有一个 indications_and_usage 成员,这就是你想要的。

2016-02-21 19:43:11