【问题标题】:parse PHP curl response as array?将 PHP curl 响应解析为数组?
【发布时间】:2016-03-06 22:20:16
【问题描述】:

解决方案 用解决方案编辑。

不知道我是否必须回答,或编辑,或什么。

问题是该服务有时会回答标题,而其他人也会回答正文。

在我的具体情况下,我使用这个建立在 SO 上的 sn-ps 解决了。

通过这个函数,我得到了答案的主体。

function get_body_from_curl_response($response){
    list($header, $body) = explode("\r\n\r\n", $response, 2);
    return $body;
}

通过这个函数,我得到了一个标题的 assoc 数组。

function get_headers_from_curl_response($response)
{
    $headers = array();
    $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
    foreach (explode("\r\n", $header_text) as $i => $line)
        if ($i === 0)
            $headers['http_code'] = $line;
        else
        {
            list ($key, $value) = explode(': ', $line);

            $headers[$key] = $value;
        }
    return $headers;
}

-- 最初的问题。

我正在尝试与 REST 服务通信,但不了解如何解析响应。从服务的 python 示例中,我看到管理类似于数组的响应非常容易,但是从 php 中我只得到一个大文本,我必须以某种方式解析。

答案类似于 http://www.valentina-db.com/docs/dokuwiki/v6/doku.php?id=valentina:articles:vserver_rest&s[]=rest

有一些方法可以像 python 中的 urllib2 那样解析 curl 输出吗?

更新

我的代码

$data = array("user" => "sa", "password" => md5("sa"));

$data_string = json_encode($data);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://127.0.0.1:8888/rest');
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch2, CURLOPT_HEADER, true);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'Content-Type: application/json'
));

$result = curl_exec($ch2);

echo 'Result <br>';
var_dump  ( $result ) ;
echo '<br>--------- <br>';

$json_answer = json_decode( $result, true );
echo ' <br> json answer <br>';
print_r ( $json_answer );
echo '<br>--------- <br>';
echo ' <br> json error <br>';

print_r ( json_last_error_msg() );

echo '<br>--------- <br>';

curl_close($ch2);

这是输出

Result
irrelevant_path\index.php:1155: string(140) "HTTP/1.1 201 Created Location: /rest/session_b4b8e5ce3f709c452b3dfc94e9273a0d; Set-Cookie: sessionID=b4b8e5ce3f709c452b3dfc94e9273a0d; "
---------

json answer

---------

json error
Syntax error
--------- 

【问题讨论】:

  • 看起来它正在返回 JSON 格式的数据字符串(就像大多数 RESTful API 所做的那样),所以 json_decode() 就是您要查找的内容。
  • 这是我的想法,但不起作用。我更新了使用的代码和输出。
  • $result 周围添加一个pre 标记并重新发布输出。看起来您收到的是重定向,而不是 JSON 响应。

标签: php curl


【解决方案1】:

您似乎在 JSON 中得到答案,您可以使用

将其转换为数组

json_decode($json_data) 它将json数据转换为数组格式。

希望对你有帮助

【讨论】:

  • 实际上它会将它转换为一个对象。对于数组,您必须将 true 作为第二个参数传入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多