无法通过变量解码json字符串

时间:2013-05-08 04:08:02

标签: php arrays json

$result = json_decode(file_get_contents('route.json'),true);

// the json file is here: http://myweb.polyu.edu.hk/~11010482d/FSP/route.json

print_r($result);

//it show '[{"X":"264","Y":"115"},{"X":"328","Y":"115"},{"X":"309","Y":"216"},{"X":"256","Y":"222"},{"X":"227","Y":"217"},{"X":"227","Y":"238"},{"X":"223","Y":"221"},{"X":"223","Y":"205"},{"X":"254","Y":"206"},{"X":"309","Y":"182"},{"X":"309","Y":"98"},{"X":"327","Y":"98"}]'

//i have tried the string not using $result as variable to decode and it works.

$abcdefg = json_decode('[{"X":"264","Y":"115"},{"X":"328","Y":"115"},{"X":"309","Y":"216"},{"X":"256","Y":"222"},{"X":"227","Y":"217"},{"X":"227","Y":"238"},{"X":"223","Y":"221"},{"X":"223","Y":"205"},{"X":"254","Y":"206"},{"X":"309","Y":"182"},{"X":"309","Y":"98"},{"X":"327","Y":"98"}]',true);

print_r($abcdefg);

//it show Array ( [0] => Array ( [X] => 264 [Y] => 115 ) [1] => Array ( [X] => 328 [Y] => 115 ) [2] => Array ( [X] => 309 [Y] => 216 ) [3] => Array ( [X] => 256 [Y] => 222 ) [4] => Array ( [X] => 227 [Y] => 217 ) [5] => Array ( [X] => 227 [Y] => 238 ) [6] => Array ( [X] => 223 [Y] => 221 ) [7] => Array ( [X] => 223 [Y] => 205 ) [8] => Array ( [X] => 254 [Y] => 206 ) [9] => Array ( [X] => 309 [Y] => 182 ) [10] => Array ( [X] => 309 [Y] => 98 ) [11] => Array ( [X] => 327 [Y] => 98 ) )
// and i want this result for the previous way.

2 个答案:

答案 0 :(得分:0)

请试试这个:

<?php
$json=file_get_contents('http://myweb.polyu.edu.hk/~11010482d/FSP/route.json');
$json=substr($json,1,-1);

$result = json_decode($json,true);

print_r($result);
?>

答案 1 :(得分:0)

试试这个

<?php
$string =  file_get_contents('http://myweb.polyu.edu.hk/~11010482d/FSP/route.json');
$result = json_decode(trim($string,"'"),true);
print_r($result);
?>

实际问题是你的网址中的json在它周围有引号..这使得json无效..