在PHP中解析HTTP Web服务(JSON)的响应

4

我需要消费一个返回JSON格式响应的HTTP Web服务。如果已知Web服务的URL,我如何在php中实现这一点?

4个回答

10

这是您应该做的:

$data = file_get_contents(<url of that website>);
$data = json_decode($data, true); // Turns it into an array, change the last argument to false to make it an object

这应该可以将JSON数据转换为数组。

现在,我们来解释下它的作用。

file_get_contents()本质上是获取文件的内容,无论是远程还是本地。这是通过HTTP门户网站完成的,因此使用此函数从远程内容获取信息不会违反隐私政策。

然后,当您使用json_decode()函数时,通常会将JSON文本更改为PHP对象,但由于我们为第二个参数添加了true,它将返回一个关联数组。

然后您就可以对该数组进行任何操作了。

玩得愉快!


2
    // setup curl options
    $options = array(
        CURLOPT_URL => 'http://serviceurl.com/api',
        CURLOPT_HEADER => false,
        CURLOPT_FOLLOWLOCATION => true
    );

    // perform request
    $cUrl = curl_init();
    curl_setopt_array( $cUrl, $options );
    $response = curl_exec( $cUrl );
    curl_close( $cUrl );

    // decode the response into an array
    $decoded = json_decode( $response, true );

2

您需要使用json_decode()函数解析响应,然后将其作为PHP数组进行处理。


2
首先使用curl读取响应,然后使用json_decode()解析使用curl获取的响应。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接