【发布时间】: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 响应。