在PHP中解析来自HTTP web服务(JSON)的响应

在PHP中解析来自HTTP web服务(JSON)的响应,php,json,web-services,http,Php,Json,Web Services,Http,我需要使用一个HTTP Web服务,其响应为JSON格式。在已知web服务的URL的情况下,如何在php中实现这一点 您需要json\u decode()响应,然后将其作为一个php数组进行处理首先使用读取响应。然后,使用json_decode()解析使用curl得到的响应。这是您应该做的: $data = file_get_contents(<url of that website>); $data = json_decode($data, true); // Turns it i

我需要使用一个HTTP Web服务,其响应为JSON格式。在已知web服务的URL的情况下,如何在php中实现这一点

您需要
json\u decode()
响应,然后将其作为一个php数组进行处理

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

这是您应该做的:

$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
$data=file_get_contents();
$data=json_decode($data,true);//将其转换为数组,将最后一个参数更改为false以使其成为对象
这应该能够将JSON数据转换为数组

现在,解释一下它的作用

file\u get\u contents()
基本上获取文件的内容,无论是远程的还是本地的。这是通过HTTP门户实现的,因此您对远程内容使用此功能不会违反隐私策略

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

然后你可以用数组做任何事情

玩得开心

    // 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 );