用PHP5的SimpleXML解析XML文檔_PHP教程
推薦:使用PHP生成1000個隨機(jī)注冊碼一般程序中都需要用到注冊碼,為了防止盜版,如果把生成的注冊碼保存到數(shù)據(jù)庫里,并且通過軟件在客戶端訪問服務(wù)器來匹配客戶端輸入的驗證碼是否正確,這是一種好的解決盜版的方案。 下面描述
以下為引用的內(nèi)容: messages.xml ======================================================== <?xml version="1.0" ?> <!--Sample XML document --> <SystemMessage> <MessageTitle>System Down for Maintenance</MessageTitle> <MessageBody>Going down for maintenance soon!</MessageBody> <MessageAuthor> <MessageAuthorName>Joe SystemGod</MessageAuthorName> <MessageAuthorEmail>systemgod@someserver.com </MessageAuthorEmail> </MessageAuthor> <MessageDate>March 4, 2004</MessageDate> <MessageNumber>10</MessageNumber> </SystemMessage> ======================================================== |
xml 是一種創(chuàng)建元數(shù)據(jù)的語言,元數(shù)據(jù)是描述其它數(shù)據(jù)的數(shù)據(jù),PHP中的XML處理是基于LIBXML2的,安裝時默認(rèn)開啟。
可以通過phpinfo()函數(shù)查看是否開啟了XML處理模塊,DOM,LIBXML,SAMPLEXML。
首先,通過samplexml_load_file函數(shù)把xml文件加載到一個對象中,samplexml_load_file可以用戶遠(yuǎn)程文件。
例如:
$xml = samplexml_load_file("messages.xml"); // 本地文件系統(tǒng),當(dāng)前目錄
$xml = samplexml_load_file("http://www.xml.org.cn/messages.xml"); // 遠(yuǎn)程web服務(wù)器
用 var_dump($xml) 和 print_r($xml) 分別輸出其結(jié)構(gòu).var_dump給出了變量的類型和長度,而print_r可讀性更強(qiáng)輸出對象中的所有元素名稱和它的值。
echo $xml->MessageTitle; //輸出消息的標(biāo)題
echo $xml->MessageBody; // 輸出消息體
echo $xml->MessageAuthor; //消息的作者
echo $xml->MessageDate; // 消息產(chǎn)生的日期
echo $xml->MessageNumber; // 消息代碼
===================================================
另外,還有一個函數(shù),可以把XML字符串加載到一個simplexml對象中取。
以下為引用的內(nèi)容: $channel =<<<_XML_ $xml = simplexml_load_string($channel);
rss.xml ============================================= |
1、訪問具有相同元素名稱的節(jié)點
2、通過foreach循環(huán)所有相同元素名稱的子節(jié)點
以下為引用的內(nèi)容: foreach($xml->channel->item as $key=>$value) { print "Title: " . $item->title . "\n"; } |
3、輸出整個文檔
echo $xml->asXML();
4、把節(jié)點作為字符串輸出
echo $xml->channel->item[0]->asXML();
這將輸出文本
以下為引用的內(nèi)容: <item> <title>Braised Sea Cucumber</title> <link>http://menu.example.com/dishes.php?dish=cuke</link> <description>Gentle flavors of the sea that nourish and refresh you. </description> </item> |
帶文件名參數(shù)的asXML將會把原本輸出的內(nèi)容保存為一個文件
$xml->channel->item[0]->asXML("item[0].xml");
完整的代碼:
以下為引用的內(nèi)容: rss.xml rss.php echo "<h3>".$xml->channel->title."</h3><br>"; foreach ($xml->channel->item[0] as $element_name => $content) { echo "<hr>"; |
任何XML文本在輸出前最好用 htmlentiteis() 函數(shù)編碼后再輸出,否這可能出現(xiàn)問題
分享:新手通過實例學(xué)習(xí)動態(tài)網(wǎng)頁PHP的語法以下為引用的內(nèi)容: <?php echo "Hello, World!"; ?> 運行結(jié)果: Hello, World! 變量標(biāo)記為“
- PHPNOW安裝Memcached擴(kuò)展方法詳解
- php記錄頁面代碼執(zhí)行時間
- PHP中獎概率的抽獎算法程序代碼
- apache設(shè)置靜態(tài)文件緩存方法介紹
- php對圖像的各種處理函數(shù)代碼小結(jié)
- PHP 關(guān)于訪問控制的和運算符優(yōu)先級介紹
- 關(guān)于PHP語言構(gòu)造器介紹
- php/js獲取客戶端mac地址的實現(xiàn)代碼
- php5.5新數(shù)組函數(shù)array_column使用
- PHP preg_match的匹配多國語言的技巧
- php 中序列化和json使用介紹
- php采集文章中的圖片獲取替換到本地
- 相關(guān)鏈接:
- 教程說明:
PHP教程-用PHP5的SimpleXML解析XML文檔。