分享一個可以跟json一樣用的函數jsonp_decode,能把jsonp格式數據轉為php數組或對象。
/**
* 把jsonp轉為php數組
* @param string $jsonp jsonp字符串
* @param boolean $assoc 當該參數為true時,將返回array而非object
* @return array
*/
function
jsonp_decode(
$jsonp
,
$assoc
= false)
{
$jsonp
= trim(
$jsonp
);
if
(isset(
$jsonp
[0]) &&
$jsonp
[0] !==
'['
&&
$jsonp
[0] !==
'{'
) {
$begin
=
strpos
(
$jsonp
,
'('
);
if
(false !==
$begin
)
{
$end
=
strrpos
(
$jsonp
,
')'
);
if
(false !==
$end
)
{
$jsonp
=
substr
(
$jsonp
,
$begin
+ 1,
$end
-
$begin
- 1);
}
}
}
return
json_decode(
$jsonp
,
$assoc
);
}