php - PHP - 从 curl 响应中获取特定值
问题描述
我将数组输出的 json decode 设置为 true。这是使用 curl 的以下响应格式:
{
"process_time": 0.018849853,
"data": [
{
"id": "recent_search",
"name": "",
"items": []
},
{
"id": "recent_view",
"name": "",
"items": []
},
{
"id": "popular_search",
"name": "",
"items": []
},
{
"id": "digital",
"name": "DIGITAL",
"items": []
},
{
"id": "autocomplete",
"name": "AUTOCOMPLETE",
"items": [
{
"keyword": "tas wanita batam",
"url": "/search?q=tas+wanita+batam&source=universe&st=product",
},
{
"keyword": "tas wanita import",
"url": "/search?q=tas+wanita+import&source=universe&st=product",
},
{
"keyword": "tas wanita murah",
"url": "/search?q=tas+wanita+murah&source=universe&st=product",
},
{
"keyword": "tas wanita branded",
"url": "/search?q=tas+wanita+branded&source=universe&st=product",
},
{
"keyword": "tas wanita fossil",
"url": "/search?q=tas+wanita+fossil&source=universe&st=product",
}
]
}
]
}
我的 PHP 代码:
<?php
$url = 'hxxp://domain.com/univ/v8?q=tas+wanita';
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r=curl_exec($ch);
curl_close($ch);
print_r(json_decode($r, true));
?>
我只想将零件项目“关键字”保存在 php 变量中。
我该怎么做?最好的方法是什么?
解决方案
<?php
$url = 'hxxp://domain.com/univ/v8?q=tas+wanita';
$ch=curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$r=curl_exec($ch);
curl_close($ch);
$data = json_decode($r, true);
$i=0;
foreach($data['data'] as $val) {
foreach($val['items'] as $key => $item) { //it may give warning because empty array (i.e items = [].
$keywords[$i] = $item['keyword']; // this will store keyword in $keywords array.
$i++;
}
}
$message = '<html><body>';
$message .= '<table border="1" cellpadding="10">';
$message .= "<tr><th><strong>Sr. No.:</strong> </th><th>
<strong>Keyword</strong> </th></tr>";
foreach ($keywords as $key => $value) {
$message .= "<tr><td>".$key." </td><td>" .$value. "</td></tr>";
}
$message .= "</table>";
$message .= "</body></html>";
echo $message;
?>
foreach构造提供了一种迭代数组的简单方法。foreach 仅适用于数组和对象,当您尝试在具有不同数据类型的变量或未初始化的变量上使用它时会发出错误。
推荐阅读
- ios - 一次连续表演两次
- javascript - 传单 - geoJSON 多边形内的点选择
- php - Symfony 4 - PHP 7.3 - 身份验证/令牌/AbstractToken.php 中的错误
- jquery - jquery动态添加的行是重叠行c#
- sql - 如何仅选择具有至少 2 个非缺失值的行
- javascript - Google Chrome 扩展从 LINK 获取子属性标题
- sql-server - T-SQL - 关键字“触发器”附近的语法不正确,需要外部
- python - 如何使用 OpenCensus 发送指标
- .net-core - 清理 EF Core 的 GetDbConnection?
- apache-zookeeper - 当 ZooKeeper 追随者被删除时会发生什么?