俺家里htpc装的xbmc,很炫的一个媒体播放器。
一直想把里面的内容拽出来给朋友分享,前两天找到了个php的库,可以直接用xbmc提供的jsonrpc。于是git下来试了试,花了半天时间,搞定。中间遇到两个问题。
1、连接不上服务器,测了半天,发现在这个rpc/Client.php loadAvailableCommands上挂掉,提示Invalid Params:
private function loadAvailableCommands() {
try {
$response = $this->sendRpc('JSONRPC.Introspect');
} catch (XBMC_RPC_Exception $e) {
throw new XBMC_RPC_RequestException(
'Unable to retrieve list of available commands: ' . $e->getMessage()
);
}
google一下儿,发现了这个, JSON RPC: Important changes , 喵的,竟然换了接口,于是加上了参数。
private function loadAvailableCommands() {
try {
$response = $this->sendRpc('JSONRPC.Introspect',
array('getdescriptions' => 'True', 'getmetadata' => 'False'));
} catch (XBMC_RPC_Exception $e) {
throw new XBMC_RPC_RequestException(
'Unable to retrieve list of available commands: ' . $e->getMessage()
);
}
搞定。
2、中文乱码,继续debug,发现在这个函数之前字符是正确的。
/**
* Takes a JSON string as returned from the server and decodes it into an
* associative array.
*/
private function decodeResponse($json) {
if (extension_loaded('mbstring')) {
$encoding = mb_detect_encoding($json,
'ASCII,utf-8,ISO-8859-1,windows-1252,iso-8859-15');
if ($encoding && !in_array($encoding, array('utf-8', 'ASCII'))) {
$json = mb_convert_encoding($json, 'utf-8', $encoding);
}
}
$r = json_decode($json, true);
return $r;
}
出错的主要原因试$json中的中文本身已经试utf-8的了,但是mb_detect_encoding检测的结果,$json的编码是iso-8859-1,于是在mb_convert_encoding一下儿,就彻底乱套了。继续google,一大堆推荐我用url_encode来解决这个问题的。最终找到一个靠谱的。做个小修改。
/**
* Takes a JSON string as returned from the server and decodes it into an
* associative array.
*/
private function decodeResponse($json) {
if (extension_loaded('mbstring')) {
$encoding = mb_detect_encoding($json,
'ASCII,utf-8,ISO-8859-1,windows-1252,iso-8859-15');
if ($encoding && !in_array($encoding, array('utf-8', 'ASCII'))) {
$json = mb_convert_encoding($json, 'utf-8', 'auto');
}
}
$r = json_decode($json, true);
return $r;
}
事实证明mb_convert_encoding直接auto效果很好,呵呵,搞定。







