I’m trying to decode a selenium server’s response. The server returns:
{"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}
and i’m trying to decode it with the following:
$json = json_decode($s->result);
echo '<pre>'.print_r($json, 1).'</pre>';
At this stage the $s object is:
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] =>
)
However when I actually paste the results into json_decode() it does it just fine? Where am I going wrong?
I would guess that
$s->resultis the HTML response body, and it’s not coming back as UTF-8–encoded data (sojson_encodereturnsNULL). This is an issue on the server side, as JSON should be UTF-8–encoded. Ideally, the server would respond with a Content-Type header telling you the encoding of the response body.However, you can work around the issue by calling
utf8_encodeon the response: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:If all else fails, have a look at the output of 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 withstr_replace("\0", '', $s->result).