【问题标题】:Parsing response from a HTTP web service (JSON) in PHP在 PHP 中解析来自 HTTP Web 服务 (JSON) 的响应
【发布时间】:2013-07-23 13:35:55
【问题描述】:

我需要使用一个以 JSON 格式响应的 HTTP Web 服务。鉴于 Web 服务的 URL 已知,我如何在 php 中实现这一点?

【问题讨论】:

    标签: php json web-services http


    【解决方案1】:

    这是你应该做的:

    $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】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:
              // 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 );
          

          【讨论】:

            猜你喜欢
            • 2011-02-10
            • 1970-01-01
            • 2013-08-05
            • 1970-01-01
            • 2016-04-14
            • 2013-06-23
            • 2013-01-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多