将PHP curl响应解析为数组?

将PHP curl响应解析为数组?,php,curl,Php,Curl,解决方案 用解决方案编辑 不知道我是否需要回答,编辑,或者做什么 问题是该服务有时会回答标题,而其他服务也会回答正文 在我的特定情况下,我使用基于SO的代码片段解决了这个问题 通过这个函数,我得到了答案的主体 function get_body_from_curl_response($response){ list($header, $body) = explode("\r\n\r\n", $response, 2); return $body; } 通过这个函数,我得到一个头

解决方案 用解决方案编辑

不知道我是否需要回答,编辑,或者做什么

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

在我的特定情况下,我使用基于SO的代码片段解决了这个问题

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

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中,我只得到一个大文本,我必须以某种方式进行解析

答案大概是这样的

有什么方法可以像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);

看起来您得到的答案是JSON,您可以使用

json_解码($json_数据) 它将json数据转换为数组格式


希望它能有所帮助

它看起来像是在返回JSON格式的数据字符串(就像大多数RESTful API一样),这也是您想要的。这是我的想法,但不起作用。我使用使用的代码和输出进行了更新。在
$result
周围添加一个
pre
标记,然后重新发布输出。看起来您得到的是重定向,而不是JSON响应。实际上,它会将其转换为对象。对于数组,必须将true作为第二个参数传入。
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
---------