1

我正在尝试解码硒服务器的响应。服务器返回:

{"sessionId":null,"status":0,"value":{"os":{"arch":"amd64","name":
"Windows Server 2008 R2","version":"6.1"},"java":{"version":"1.7.0_02"},
"build":{"revision":"15105","time":"2011-12-08 09:56:25","version":"2.15.0"}},
"class":"org.openqa.selenium.remote.Response","hCode":1813953336}

我正在尝试使用以下内容对其进行解码:

$json = json_decode($s->result);
echo '<pre>'.print_r($json, 1).'</pre>';

在这个阶段,$s 对象是:

Scrape Object
(
    [headers] => Array
        (
        )

    [result] => {"sessionId":null,"status":0,"value":{"os":{"arch":"amd64","name":"Windows Server 2008 R2","version":"6.1"},"java":{"version":"1.7.0_02"},"build":{"revision":"15105","time":"2011-12-08 09:56:25","version":"2.15.0"}},"class":"org.openqa.selenium.remote.Response","hCode":287101789}
    [http_code] => 200
    [error] => 
)

但是,当我实际将结果粘贴到 json_decode() 中时,它就可以了吗?我哪里错了?

4

1 回答 1

3

我猜那$s->result是 HTML 响应正文,它不会以 UTF-8 编码数据的形式返回(所以json_encode返回NULL)。这是服务器端的问题,因为 JSON 应该是 UTF-8 编码的。理想情况下,服务器会响应一个 Content-Type 标头,告诉您响应正文的编码。

utf8_encode但是,您可以通过调用响应来解决此问题:

$json = json_decode(utf8_encode($s->result));
echo '<pre>' . print_r($json, 1) . '</pre>';

This will only work if the response is in ISO-8859-1. As an additional check, you may want to detect the encoding of the response using mb_detect_encoding. You can then pass the result into iconv:

$json = json_decode(iconv($sourceEncoding, 'UTF-8', $s->result));
echo '<pre>' . print_r($json, 1) . '</pre>';

If all else fails, have a look at the output of json_last_error:

if ($json === null) {
    var_dump(json_last_error());
}

EDIT: The error in this case was JSON_ERROR_CTRL_CHAR; the response contained a number of NUL characters, which were removed with str_replace("\0", '', $s->result).

于 2011-12-29T23:57:43.260 回答