php解析JSON与XML的小例子

发布时间:2020-08-03编辑:脚本学堂
php解析JSON与XML的小例子

php解析JSON与XML的小例子,供大家学习参考。

1、解析JSON数据
 

复制代码 代码示例:
<?php
$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php
?>

2、解析XML 数据

I)、xml文件
 

复制代码 代码示例:
$xml_string="<?xml version='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>";

II)、解析xml的代码
 

复制代码 代码示例:

<?php
//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user['id'], ' ';
//subnodes are accessed by -> operator
echo $user->name, ' ';
echo $user->email, '<br />';
}
?>