PHP解析JSON与XML
PHP解析JSON数据:
|
1
2
3
4
|
$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';$obj=json_decode($json_string);echo $obj->name; //prints fooecho $obj->interest[1]; //prints php |
PHP解析XML 数据:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
$xml_string="<?xmlversion='1.0'?><users> <user id='398'> <name>Foo</name> <email>foo@bar.com</name> </user> <user id='867'> <name>Foobar</name> <email>foobar@foo.com</name> </user></users>"; //load the xml string using simplexml$xml = simplexml_load_string($xml_string); //loop through the each node of userforeach ($xml->user as $user){ //access attribute echo $user['id'], ' '; //subnodes are accessed by -> operator echo $user->name, ' '; echo $user->email, '<br />';} |
php对url返回的json格式数据解析示例:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
$lines_array = file($url);$lines_string = implode('',$lines_array); $json = htmlspecialchars($lines_string,ENT_NOQUOTES);$J = json_decode($json);$content = $J->weatherinfo;$city = $content->city; //城市名$temp1 = $content->temp1;$temp2 = $content->temp2;$m = strpos($temp1,'℃');//寻找位置if ($m) $temp1 = substr($temp1,0,$m);//删除后面$n = strpos($temp2,'℃');//寻找位置if ($n) $temp2 = substr($temp2,0,$n);//删除后面$temp = ($temp1+$temp2)/2; //平均温度$weather = $content->weather; //天气状况$weatherinfo = array();$weatherinfo['city'] = $city;$weatherinfo['temp'] = (string)$temp;$weatherinfo['weather'] = $weather; dump($weatherinfo); |

浙公网安备 33010602011771号