$xmlstring=<<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>xuduowei</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don’t forget the meeting!</body>
</note>
XML;
$xml = simplexml_load_string($xmlstring);
var_dump($xml);
输出:
object(SimpleXMLElement)#1 (4) { [“to”]=> string(4) “George” [“from”]=> string(4) “John” [“heading”]=> string(8) “Reminder” [“body”]=> string(29) “Don’t forget the meeting!” }
$xmlstring = <<<XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>xuduowei</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don’t forget the meeting!</body>
</note>
XML;
$xml = simplexml_load_string($xmlstring);
//$xml = simplexml_load_string($xmlstring,'SimpleXMLElement',LIBXML_NOCDATA);
echo $xml->to;
php 的simplexml_load_string后两个参数有什么用处?
第二个参数表示解析所使用的类,类必须继承于SimpleXMLElement,而默认值就是SimpleXMLElement。
第三个参数表示解析的选项,LIBXML_NOCDATA表示不对CDATA进行转意,而是把他当成普通的文本进行解析。
假设XML节点里面如果有<goods_name><![CDATA[小牛N1]]></goods_name>,那么最终转换成对象里面是没有goods_name这个值
的,如果加了LIBXML_NOCDATA,值为小牛N1,相当于把<![CDATA[小牛N1]]>转换成了文本返回
xml 是一种创建元数据的语言,元数据是描述其它数据的数据,PHP中的XML处理是基于LIBXML2的,安装时默认开启。
可以通过phpinfo()函数查看是否开启了XML处理模块,DOM,LIBXML,SAMPLEXML。
首先,通过samplexml_load_file函数把xml文件加载到一个对象中,samplexml_load_file可以用户远程文件.
例如:
$xml = samplexml_load_file(“messages.xml”); // 本地文件系统,当前目录
$xml=simplexml_load_file(“http://www.xuduowei.com/tc/cs.xml”);//远程服务器上的
用 var_dump($xml) 和 print_r($xml) 分别输出其结构.var_dump给出了变量的类型和长度,而print_r可读性更强
输出对象中的所有元素名称和它的值.
echo $xml->MessageTitle; //输出消息的标题
echo $xml->MessageBody; // 输出消息体
echo $xml->MessageAuthor; //消息的作者
echo $xml->MessageDate; // 消息产生的日期
echo $xml->MessageNumber; // 消息代码
$xml=”<GetLatestContestAppResp>
<ret>0</ret>
<LatestContestApp>
<ContestApp>
<UserId>111</UserId>
<RealName>张三</RealName>
<AppName>battlefield1942</AppName>
</ContestApp>
<ContestApp>
<UserId>222</UserId>
<RealName>李四</RealName>
<AppName>battlefield II</AppName>
</ContestApp>
<ContestApp>
<UserId>333</UserId>
<RealName>王五</RealName>
<AppName>battlefield 1943</AppName>
</ContestApp>
… …
</LatestContestApp>
</GetLatestContestAppResp>”;
$xml_arr = simplexml_load_string($xml);
//print_r($xml_arr);
//echo count($xml_arr->LatestContestApp->ContestApp).”==”; //总数计算
//echo $xml_arr->LatestContestApp->ContestApp[1]->UserId;//取得相应的节点值