PHP中,如何吧返回的json对象转数组

再爬取一些网页的时候,返回的数据经常是json对象,例如:

var json={rank:["0022562,002256,兆新股份,2.65,2.79,2.92,2.92,2.66,16703,590878,0.27,10.19%,2.83,9.81,100.00,196178,951,262080,328798,-1,0,0.00,0.94,4.25,-,001153|002538|003549|003571,2.92,-,2019-08-21 15:00:00,0,1882411872,5496642810,12.56"],pages:3694}

我们会发现大括号里面的内容对于php来说不是标准的json格式,所以我们得先处理下:

1: 提取我们需要的内容
$ret = explode("=", $data);
$str = $ret[1];

2: 正则匹配,替换成我们需要的数据形式
$str2 = preg_replace(["/([a-zA-Z_]+[a-zA-Z0-9_])\s:/", "/:\s'(.?)'/"], ['"\1":', ': "\1"'], $str);
得到结果如下:
{"rank":["0022562,002256,兆新股份,2.65,2.79,2.92,2.92,2.66,16703,590878,0.27,10.19%,2.83,9.81,100.00,196178,951,262080,328798,-1,0,0.00,0.94,4.25,-,001153|002538|003549|003571,2.92,-,2019-08-21 15:00:00,0,1882411872,5496642810,12.56"],"pages":3694}

3: $ret = json_decode($str2,true);

发表评论

电子邮件地址不会被公开。 必填项已用*标注