我目前正在使用NewYorkTimes新闻API。我收到了这个JSON响应。现在我想使用PHP遍历它并获取每篇文章(图像,标题和摘录)。
{
"status": "OK",
"copyright": "Copyright (c) 2017 The New York Times Company. All Rights Reserved.",
"response": {
"docs": [
{
"web_url": "https://www.nytimes.com/reuters/2017/11/15/business/15reuters-square-bitcoin.html",
"snippet": "Payments company Square Inc said it has started allowing select customers to buy and sell bitcoins on its Cash app, as it looks to tap into a craze that has sent the cryptocurrency up nearly sevenfold this year.",
"blog": {},
"source": "Reuters",
"multimedia": [],
"headline": {
"main": "Payments Company Square Tests Bitcoin Buying and Selling",
"print_headline": "Payments Company Square Tests Bitcoin Buying and Selling"
},
"keywords": [],
"pub_date": "2017-11-15T18:24:36+0000",
"document_type": "article",
"new_desk": "None",
"byline": {
"original": "By REUTERS"
},
"type_of_material": "News",
"_id": "5a0c866b7c459f246b6349f9",
"word_count": 388,
"score": 2.5538578,
"uri": "nyt://article/1dff4a88-4086-507c-b644-33e0d7d95e28"
},
{
"web_url": "https://www.nytimes.com/reuters/2017/11/13/business/13reuters-investment-summit-fink-bitcoin.html",
"snippet": "Bitcoin, whose value has fluctuated significantly this month, remains a \"speculative\" investment that thrives because of the cryptocurrency's anonymous nature, BlackRock Inc Chief Executive Larry Fink said on Monday.",
"blog": {},
"source": "Reuters",
"multimedia": [],
"headline": {
"main": "BlackRock's Fink Says Bitcoin Thrives on Its Anonymity",
"print_headline": "BlackRock's Fink Says Bitcoin Thrives on Its Anonymity"
},
"keywords": [],
"pub_date": "2017-11-13T17:45:33+0000",
"document_type": "article",
"new_desk": "None",
"byline": {
"original": "By REUTERS"
},
"type_of_material": "News",
"_id": "5a09da4a7c459f246b63428d",
"word_count": 322,
"score": 2.5538578,
"uri": "nyt://article/bb396871-c686-5afc-9e71-3f9f5af8dac1"
}
],
"meta": {
"hits": 959,
"offset": 0,
"time": 7
}
}
}
首先,我使用$arr = json_decode($result);
来解码我的json。
但是当我试图制作一个循环时,它并没有给我任何回报
foreach($arr['docs'] as $article){
echo $article['web_url'];
}
请帮我循环查看此JSON响应并获取必要的数据。谢谢!
答案 0 :(得分:1)
试试这个
$json = json_decode($response, true);
foreach($json['response']['docs'] as $key => $value)
{
if(!empty($value['web_url']))
{
$WEB= $value['web_url'];
$WEB= addslashes($WEB);
$WEB= trim(preg_replace('/\s\s+/', ' ', $WEB));
}
else
{
$WEB= '';
}
echo 'WEB= '.$WEB.'</br>';
}
只要确保foreach是真的,也许可以提供帮助。