繁体   English   中英

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

[英]Parsing response from a HTTP web service (JSON) in PHP

我需要使用以JSON格式响应的HTTP Web服务。 考虑到Web服务的URL已知,我怎样才能在php中实现这一点?

这是你应该做的:

$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 ,因此它返回一个关联数组。

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

玩得开心!

你需要json_decode()响应,然后你把它作为一个PHP数组来处理它

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM