php - 如何在php中从json bing响应中获取特定的节点值
问题描述
我正在尝试使用 bing 搜索 API,我得到了 JSON 格式的结果,现在我想从该 JSON 结果中获取特定的节点值,例如(url、displayurl、snippet 等)。
这是我得到的 JSON 结果格式
JSON响应:
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "infokart India Pvt. Ltd."
},
"webPages": {
"webSearchUrl": "https://www.bing.com/search?q=infokart+India+Pvt.+Ltd.",
"totalEstimatedMatches": 12200000,
"value": [
{
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
"name": "Infokart India Pvt. Ltd.",
"url": "http://infokartindia.com/",
"isFamilyFriendly": true,
"displayUrl": "infokartindia.com",
"snippet": "Journals Subscription Services,International Subscription Agency,Experiences subscription agency",
"dateLastCrawled": "2018-07-24T11:49:00.0000000Z",
"language": "en"
}
]
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0"
}
}
]
}
}
}
请推荐!!
解决方案
<?php
$json = '{"_type":"SearchResponse","queryContext":{"originalQuery":"infokart India Pvt. Ltd."},"webPages":{"webSearchUrl":"https://www.bing.com/search?q=infokart+India+Pvt.+Ltd.","totalEstimatedMatches":12200000,"value":[{"id":"https://api.cognitive.microsoft.com/api/v7/#WebPages.0","name":"Infokart India Pvt. Ltd.","url":"http://infokartindia.com/","isFamilyFriendly":true,"displayUrl":"infokartindia.com","snippet":"Journals Subscription Services,International Subscription Agency,Experiences subscription agency","dateLastCrawled":"2018-07-24T11:49:00.0000000Z","language":"en"}]},"rankingResponse":{"mainline":{"items":[{"answerType":"WebPages","resultIndex":0,"value":{"id":"https://api.cognitive.microsoft.com/api/v7/#WebPages.0"}}]}}}';
$json_data = json_decode($json,true);
foreach($json_data['webPages']['value'] as $each_data){
foreach($each_data as $each_key => $each_value){
if(in_array(strtolower($each_key),['url','displayurl','snippet'])){
echo $each_key," => ",$each_value,"<br/>";
}
}
}
输出
url => http://infokartindia.com/
displayUrl => infokartindia.com
snippet => Journals Subscription Services,International Subscription Agency,Experiences subscription agency
推荐阅读
- c# - 单击按钮后如何禁用按钮游戏对象。换句话说,有一个只能点击一次的按钮
- python - 在目标移动时单击目标(图像)
- javascript - 开玩笑测试和纯 js 访问 dom 元素失败
- html - CSS BUG:溢出:隐藏;在边框旁边留下空白区域(div 内的 div)
- javascript - 为未出现在不同数组中的对象过滤现有数组
- mongodb - 使用 WHERE 条件计数
- scikit-learn - 如何为使用“sklearn.svm.SVC”创建的分类器提取内核矩阵?
- oracle - Oracle 代理会话与连接池不兼容
- java - 无法从资源文件夹中获取文件
- django - nginx中的文件名重复