PHP程序WordPress如何通过API接口读取JSON数据
我们如果想做一个资源共享的网站,就离不开json,通过API接口来读取JSON数据信息。那么对于PHP程序开发的网站,PHP怎么通过API接口读取JSON数据呢?
下面是一段PHP通过API接口读取JSON数据的实例代码,(使用WORDPRESS程序开发)供大家使用。(如果不是Wordpress程序,可以使用使用file_get_contents()函数替换wp_remote_retrieve_body( wp_remote_get()函数)
<?php
$content = wp_remote_retrieve_body( wp_remote_get('http://API接口地址') );
$content_obj = json_decode($content); #JSON内容转换为PHP对象
$timer = $content_obj->time;
$number = $content_obj->number;
$datar = $content_obj->data;
echo $timer.'|'.$number.'|'.$datar.'||';
?>
代码介绍:
先是通过WORDPRESS程序自带的wp_remote_retrieve_body函数来获取JSON的内容;
再通过json_decode将JSON内容转换为PHP对象;
最后再输出各个PHP对象里的参数值。
以上是通过PHP获取简单的JSON实例代码。如果是嵌套的JSON数据,就需要使用循环来获取JSON数据。代码如下:
<?php
$content = wp_remote_retrieve_body( wp_remote_get('http://API接口地址') );
$content_obj = json_decode($content); #JSON内容转换为PHP对象
?>
<?php
foreach ($content_obj as $key => $value) {
//var_dump($value);
$canshu = $value->data;
$shuzhi = $canshu[0];
$gid = $shuzhi->gid;
$award = $shuzhi->award;
$time03 = $shuzhi->time;
$date03 = $shuzhi->date;
$nextOpenIssue = $shuzhi->nextOpenIssue;
$nextOpenTime = $shuzhi->nextOpenTime;
$secondOpenIssue = $shuzhi->secondOpenIssue;
$secondOpenTime = $shuzhi->secondOpenTime;
$award_sum = $shuzhi->award_sum;
echo $gid.'|'.$award.'|'.$time03.'|'.$date03.'|'.$nextOpenIssue.'|'.$nextOpenTime.'|'.$secondOpenIssue.'|'.$award_sum;
}
?>
如果只想获取嵌套的JSON数据中的第一条,可以这样写:
<?php
$content = file_get_contents('http://API接口地址');
var_dump($content);
$content_obj = json_decode($content); #JSON内容转换为PHP对象
$dataone = $content_obj->result;
$datatwo = $dataone->data;
$datathree= $datatwo[0];
$gid = $datathree->gid;
$award = $datathree->award;
$time03 = $datathree->time;
$date03 = $datathree->date;
$nextOpenIssue = $datathree->nextOpenIssue;
$nextOpenTime = $datathree->nextOpenTime;
$secondOpenIssue = $datathree->secondOpenIssue;
$secondOpenTime = $datathree->secondOpenTime;
$award_sum = $datathree->award_sum;
echo $gid.'|'.$award.'|'.$time03.'|'.$date03.'|'.$nextOpenIssue.'|'.$nextOpenTime.'|'.$secondOpenIssue.'|'.$award_sum;
?>