关于PHP中对JSON 格式的字符串进行编码并解析,同时可使用正则来获取内容,看示例: 字符串:
{"resp": {"userid": 0, "ret": 0, "subfile_list": [{"gcid": "78FDC87F885EBF1923A5382436419872C71C8D30", "url_hash": "13736464574634719728", "name": "BYD-01/BYD-01.avi", "index": 2, "cid": "E112D7A9BA040D70B0E2B21526239C08393DFC5A", "file_size": 1337602048, "duration": 6553502}, {"gcid": "A78B0E63F56E2F763464837C209AE3B63D14393D", "url_hash": "10856942115347464666", "name": "BYD-02/BYD-02.avi", "index": 5, "cid": "BEB495E1C450F35A3074666F1018243F81706962", "file_size": 941570998, "duration": 6646814}], "main_task_url_hash": "5800245063447153290", "info_hash": "7BD4D21057A3FE850896D2E9790D31A986C09732", "record_num": 12}}
要求:获取上述字符串中的 gcid 内容 方法一:我们可以使用正则的方式将其进行提取
$str = '{"resp": {"userid": 0, "ret": 0, "subfile_list": [{"gcid": "78FDC87F885EBF1923A5382436419872C71C8D30", "url_hash": "13736464574634719728", "name": "BYD-01/BYD-01.avi", "index": 2, "cid": "E112D7A9BA040D70B0E2B21526239C08393DFC5A", "file_size": 1337602048, "duration": 6553502}, {"gcid": "A78B0E63F56E2F763464837C209AE3B63D14393D", "url_hash": "10856942115347464666", "name": "BYD-02/BYD-02.avi", "index": 5, "cid": "BEB495E1C450F35A3074666F1018243F81706962", "file_size": 941570998, "duration": 6646814}], "main_task_url_hash": "5800245063447153290", "info_hash": "7BD4D21057A3FE850896D2E9790D31A986C09732", "record_num": 12}}';
preg_match('/"gcid":\s*"([a-zA-Z0-9]*)"/', $str, $matches);
//var_dump($obj);
print_r($matches[1]);
如果要获取name的值,则应如下表现
preg_match_all('/"name":\s*"([\w\d\.-]*)"/', $str, $matches);
//var_dump($obj);
print_r($matches[1]);
做到这里,也许你会发现当你的字符串中含有两个或更多gcid时,你就不能同时获取这些内容了,但PHP的正则就是这么的强大,你完全可以将preg_match替换成preg_match_all,就可以获取所有的gcid内容了 方法二:则利用JSON对象的属性对内容进行获取
$str = '{"resp": {"userid": 0, "ret": 0, "subfile_list": [{"gcid": "78FDC87F885EBF1923A5382436419872C71C8D30", "url_hash": "13736464574634719728", "name": "BYD-01/BYD-01.avi", "index": 2, "cid": "E112D7A9BA040D70B0E2B21526239C08393DFC5A", "file_size": 1337602048, "duration": 6553502}, {"gcid": "A78B0E63F56E2F763464837C209AE3B63D14393D", "url_hash": "10856942115347464666", "name": "BYD-02/BYD-02.avi", "index": 5, "cid": "BEB495E1C450F35A3074666F1018243F81706962", "file_size": 941570998, "duration": 6646814}], "main_task_url_hash": "5800245063447153290", "info_hash": "7BD4D21057A3FE850896D2E9790D31A986C09732", "record_num": 12}}';
$obj = json_decode($str);
//var_dump($obj);
print_r($obj->resp->subfile_list[0]->gcid);
好了,两种方法均获取成功~