XML est un format de fichier semi-structuré populaire qui stocke les données dans un format semblable à une base de données. Dans les applications pratiques, certaines données simples et peu sécurisées sont souvent stockées au format de fichier XML. L'avantage est que, d'une part, cela peut améliorer l'efficacité de la lecture en réduisant les opérations interactives avec la base de données, et d'autre part, cela peut utiliser efficacement les avantages de XML pour réduire la difficulté d'écriture du programme.
PHP fournit un ensemble complet de méthodes pour lire les fichiers XML, ce qui facilite l'écriture de scripts XML. Ce chapitre présentera les méthodes de fonctionnement de PHP et XML et donnera une brève introduction à plusieurs bibliothèques de classes XML couramment utilisées.
1 Introduction à XML
XML est l'abréviation de ? eXtensible Markup Language ? et est un langage de balisage similaire au HTML. Mais contrairement au HTML, XML est principalement utilisé pour décrire et stocker des données, tandis que HTML est principalement utilisé pour afficher des données.
XML est un langage de ? balise méta ? qui permet aux développeurs de créer des noms de balises en fonction de leurs propres besoins. Par exemple, le code XML suivant peut être utilisé pour décrire un message.
<thread>
<title>Welcome</title>
<author>Simon</author>
<content>Welcome to XML guestbook!!</content>
</thread>
Parmi eux, les balises et Il y a un titre, un auteur et un contenu dans le message, qui expriment complètement un message.
En haut d'un fichier XML, est généralement utilisé pour identifier le début des données XML et les données XML utilisent des informations de version standard. Lorsque vous accédez à un fichier XML dans un navigateur, vous pouvez voir des informations de données XML clairement structurées, comme le montre la figure 1.

XML se développe très rapidement ces dernières années, de nombreux développeurs de logiciels ont commencé à adopter les normes de développement XML pour le développement d'applications. De plus, de nombreuses technologies émergentes reposent sur des données XML. Cela signifie que XML deviendra une partie intégrante de la technologie Web au même titre que HTML.
2 Opérations XML simples
Dans les applications pratiques, le fonctionnement interactif de PHP et XML est largement utilisé. Le composant SimpleXML est un composant d'opération XML simple nouvellement ajouté dans PHP5. Par rapport aux composants XML traditionnels, l'utilisation des composants SimpleXML est très simple. Cette section donnera une introduction détaillée à la méthode d'utilisation du composant
SimpleXML pour manipuler XML.
2.1 Créer un objet SimpleXML
L'objet SimpleXML est une variable temporaire utilisée pour stocker temporairement des données XML. Les opérations sur XML sont effectuées en exploitant des objets SimpleXML. Le composant SimpleXML fournit deux méthodes pour créer des objets SimpleXML. La première méthode consiste à utiliser la fonction simplexml_load_string pour lire les données XML dans une variable cha?ne afin de terminer la création. Le format de syntaxe est le suivant.
simplexml_load_string(string data)
La variable data ici est utilisée pour stocker des données XML. Le code suivant utilise la fonction simplexml_load_string pour créer un objet SimpleXML
<?php
$data = <<<XML //定義 XML數(shù)據(jù)
<?xml version='1.0′?>
<departs>
<depart>
<name>production support</name>
<employees>
<employee>
<serial_no>100001</serial_no>
<name>Simon</name>
<age>24</age>
<birthday>1982-11-06</birthday>
<salary>5000.00</salary>
<bonus>1000.00</bonus>
</employee>
<employee>
<serial_no>100002</serial_no>
<name>Elaine</name>
<age>24</age>
<birthday>1982-01-01</birthday>
<salary>6000.00</salary>
<bonus>2000.00</bonus>
</employee>
</employees>
</depart>
<depart>
<name>testing center</name>
<employees>
<employee>
<serial_no>110001</serial_no>
<name>Helen</name>
<age>23</age>
<birthday>1983-07-21</birthday>
<salary>5000.00</salary>
<bonus>1000.00</bonus>
</employee>
</employees>
</depart>
</departs>
XML;
$xml = simplexml_load_string($data); //創(chuàng)建 SimpleXML對象
print_r($xml); //輸出 XML
?>
Dans l'exemple ci-dessus, la variable $data stocke une donnée XML. La fonction simplexml_load_string convertit la variable $data en un objet SimpleXML. La structure de l'objet peut être vue à travers la sortie de la fonction print_r, et les résultats d'exécution sont les suivants.
SimpleXMLElement Object
(
[depart] => Array
(
[0] => SimpleXMLElement Object
(
[name] => production support
[employees] => SimpleXMLElement Object
( [employee] => Array (
[0] => SimpleXMLElement Object
( [serial_no] => 100001
[name] => Simon
[age] => 24
[birthday] => 1982-11-06
[salary] => 5000.00
[bonus] => 1000.00
)
[1] => SimpleXMLElement Object
( [serial_no] => 100002
[name] => Elaine
[age] => 24
[birthday] => 1982-01-01
[salary] => 6000.00
[bonus] => 2000.00
)
)
)
)
[1] => SimpleXMLElement Object
(
[name] => testing center
[employees] => SimpleXMLElement Object
(
[employee] => SimpleXMLElement Object
(
[serial_no] => 110001
[name] => Helen
[age] => 23
[birthday] => 1983-07-21
[salary] => 5000.00
[bonus] => 1000.00
)
)
)
)
)
Comme le montrent les résultats de sortie, la structure de l'objet SimpleXML est exactement la même que le format des données XML.
La deuxième méthode consiste à utiliser la fonction simplexml_load_flie pour lire un fichier XML afin de terminer la création. Le format de syntaxe est le suivant.
simplexml_load_file(string filename)
La variable filename ici est le nom du fichier et le chemin utilisés pour stocker le fichier de données XML. Le code suivant utilise la fonction simplexml_load_file pour créer un objet SimpleXML.
<?php
$xml = simplexml_load_file('example.xml'); //創(chuàng)建 SimpleXML對象
print_r($xml); //輸出 XML
?>
Parmi eux, les données stockées dans example.xml sont exactement les mêmes que les $data ci-dessus, et les résultats d'exécution sont exactement les mêmes que ci-dessus.
Les deux méthodes ci-dessus implémentent la même fonction, la différence réside dans les différentes sources de données XML. Si la source de données XML se trouve dans un fichier de script PHP, vous devez utiliser simplexml_load_string pour la créer. Si la source de données XML se trouve dans un fichier XML distinct, vous devez utiliser simplexml_load_file pour la créer.
2.2 Lecture de données XML dans un objet SimpleXML
Auparavant, nous avons introduit l'utilisation de la fonction print_r pour lire des données dans un objet SimpleXML, et le résultat renvoyé est similaire à la structure d'un tableau. évidemment, cette méthode d’affichage n’est pas souhaitable dans les applications pratiques. Nous présenterons ici plusieurs autres méthodes de lecture de données XML dans des objets SimpleXML.
1. La fonction var_dump affiche des informations détaillées sur les objets
La fonction var_dump peut être utilisée pour afficher des informations détaillées sur les objets SimpleXML. Par rapport à la fonction print_r, la fonction var_dump affiche des informations plus complètes.
void var_dump(object1, object2 … )
Le code suivant utilise la fonction var_dump pour afficher les informations détaillées de l'objet dans l'exemple ci-dessus.
<?php $xml = simplexml_load_file('example.xml'); //創(chuàng)建 SimpleXML對象 var_dump($xml); //輸出 XML ?>
Les résultats en cours d'exécution sont les suivants.
object(SimpleXMLElement)#1 (1) { ["depart"]=> array(2) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["name"]=>
string(18) “production support”
["employees"]=>
object(SimpleXMLElement)#4 (1) {
["employee"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#5 (6) {
["serial_no"]=>
string(6) “100001″
["name"]=>
string(5) “Simon”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-11-06″
["salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}
[1]=>
object(SimpleXMLElement)#6 (6) {
["serial_no"]=>
string(6) “100002″
["name"]=>
string(6) “Elaine”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-01-01″
["salary"]=>
string(7) “6000.00″
["bonus"]=>
string(7) “2000.00″
}
}
}
}
[1]=>
object(SimpleXMLElement)#3 (2) {
["name"]=>
string(14) “testing center”
["employees"]=>
object(SimpleXMLElement)#7 (1) {
["employee"]=>
object(SimpleXMLElement)#8 (6) {
["serial_no"]=>
string(6) “110001″
["name"]=>
string(5) “Helen”
["age"]=>
string(2) “23″
["birthday"]=>
string(10) “1983-07-21″
["salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}}}}}
與前面 print_r輸出的結果相比較,var_dump函數(shù)的輸出結果的結構更為嚴謹,并且將對象中的每一個屬性的數(shù)據(jù)類型均作出分析。在實際應用中,var_dump函數(shù)往往用于程序調(diào)試時的對象檢測。
2.讀取 XML數(shù)據(jù)中的標簽
與操作數(shù)組類型的變量類似,讀取 XML也可以通過類似的方法來完成。例如,如果需要讀取上面 XML數(shù)據(jù)中每一個“ depart”標簽下的“name”屬性,可以通過使用 foreach函數(shù)來完成,如以下代碼
所示。
<?php $xml = simplexml_load_file('example.xml'); foreach($xml->depart as $a)
{
echo “$a->name <BR>”;
}
?>
運行結果如下所示。
production support
testing center
//讀取 XML文件 //循環(huán)讀取 XML數(shù)據(jù)中的每一個 depart標簽
//輸出其中的 name屬性
也可以使用方括號“ []”來直接讀取 XML數(shù)據(jù)中指定的標簽。以下代碼輸出了上面 XML數(shù)據(jù)中的第一個“depart”標簽的“name”屬性。
<?php
$xml = simplexml_load_file('example.xml'); //讀取 XML文件
echo $xml->depart->name[0]; //輸出節(jié)點
?>
運行結果如下所示。
production support
對于一個標簽下的所有子標簽,SimpleXML組件提供了 children方法進行讀取。例如,對于上面的 XML數(shù)據(jù)中的“ depart”標簽,其下包括兩個子標簽:“ name”和“employees”。以下代碼實現(xiàn)了對第一個“depart”標簽下的子標簽的讀取。
<?php
$xml = simplexml_load_file('example.xml');
foreach ($xml->depart->children() as $depart) //循環(huán)讀取 depart標簽下的子標簽
{
var_dump($depart); //輸出標簽的 XML數(shù)據(jù)
}
?>
運行結果如下所示。
object(SimpleXMLElement)#3 (1) {
[0]=>
string(18) “production support”
}
object(SimpleXMLElement)#5 (1) {
["employee"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#3 (6) {
["serial_no"]=>
string(6) “100001″
["name"]=>
string(5) “Simon”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-11-06″
["salary"]=>
string(7) “5000.00″
["bonus"]=>
string(7) “1000.00″
}
[1]=>
object(SimpleXMLElement)#6 (6) {
["serial_no"]=>
string(6) “100002″
["name"]=>
string(6) “Elaine”
["age"]=>
string(2) “24″
["birthday"]=>
string(10) “1982-01-01″
["salary"]=>
string(7) “6000.00″
["bonus"]=>
string(7) “2000.00″
}
}
}
可以看出,使用 children方法后,所有的子標簽均被當作一個新的 XML文件進行處理。
3.基于 XML數(shù)據(jù)路徑的查詢
SimpleXML組件提供了一種基于 XML數(shù)據(jù)路徑的查詢方法。 XML數(shù)據(jù)路徑即從 XML的根到某一個標簽所經(jīng)過的全部標簽。這種路徑使用斜線“ /”隔開標簽名。例如,對于上面的 XML數(shù)據(jù),要查詢所有的標簽“name”中的值,從根開始要經(jīng)過 departs、depart、employees和 employee標簽,則其路徑
為“/departs/depart/employees/employee/name”。 SimpleXML組件使用 xpath方法來解析路徑,其語法格式如下所示。
xpath(string path)
其中的 path為路徑。該方法返回了一個包含有所有要查詢標簽值的數(shù)組。以下代碼查詢了上面 XML數(shù)據(jù)中的所有 name標簽。
<?php
$xml = simplexml_load_file('example.xml'); //讀取 XML文件
$result = $xml->xpath('/departs/depart/employees/employee/name'); //定義節(jié)點
var_dump($result); //輸出節(jié)點
?>
運行結果如下所示。
array(3) {
[0]=> object(SimpleXMLElement)#2 (1) {
[0]=> string(5) “Simon”
}
[1]=> object(SimpleXMLElement)#3 (1) {
[0]=> string(6) “Elaine”
}
[2]=> object(SimpleXMLElement)#4 (1) {
[0]=> string(5) “Helen”
}
}
可以看出,所有的 name標簽均被查詢出來。
2.3 XML數(shù)據(jù)的修改
對于 XML數(shù)據(jù)的修改與讀取 XML數(shù)據(jù)中的標簽方法類似。即通過直接修改 SimpleXML對象中的標簽的值來實現(xiàn)。以下代碼實現(xiàn)了對上面 XML數(shù)據(jù)中第一個“ depart”標簽的“ name”子標簽的修改。
<?php
$xml = simplexml_load_file('example.xml'); //讀取 XML
$xml->depart->name[0] = “Human Resource”; //修改節(jié)點
?>
修改后,并不會對 XML文件有任何影響。但是,在程序中,對于 SimpleXML對象的讀取將使用修改過的值。
2.4 標準化 XML數(shù)據(jù)
SimpleXML還提供了一種標準化 XML數(shù)據(jù)的方法 asXML。asXML方法可以有效的將 SimpleXML對象中的內(nèi)容按照 XML 1.0標準進行重新編排并以字符串的數(shù)據(jù)類型返回。以下代碼實現(xiàn)了對上面 XML數(shù)據(jù)的標準化。
<?php
$xml = simplexml_load_file('example.xml'); //讀取 XML數(shù)據(jù)
echo $xml->asXML(); //標準化 XML數(shù)據(jù)
?>
2.5 XML數(shù)據(jù)的存儲
將 SimpleXML對象中的 XML數(shù)據(jù)存儲到一個 XML文件的方法非常簡單,即將 asXML方法的返回結果輸出到一個文件中即可。以下代碼首先將 XML文件中的 depart name進行了修改,然后將修改過的 XML數(shù)據(jù)輸出到另一個 XML文件。
<?php
$xml = simplexml_load_file('example.xml'); //讀取 XML數(shù)據(jù)
$newxml = $xml->asXML(); //標準化 XML數(shù)據(jù)
$fp = fopen(”newxml.xml”, “w”); //打開要寫入 XML數(shù)據(jù)的文件
fwrite($fp, $newxml); //寫入 XML數(shù)據(jù)
fclose($fp); //關閉文件
?>
代碼運行后,可以看到在 newxml.xml文件中的 XML數(shù)據(jù)如下所示。
可以看出,對于 XML文件的修改已經(jīng)保存到輸出文件中了。
3 XML文檔的動態(tài)創(chuàng)建
在實際應用中,時而會需要動態(tài)生成 XML文檔的操作。前面介紹的 SimpleXML組件并不提供創(chuàng)建 XML文檔的方法。因此,如果需要動態(tài)創(chuàng)建 XML文檔,往往使用 DOM組件進行創(chuàng)建。 DOM是文檔對象模型 Document Object Model的縮寫, DOM組件提供了對 XML文檔的樹型解析模式。以下代碼使用 DOM組件創(chuàng)建了一個 XML文檔。
<?php
//創(chuàng)建一個新的 DOM文檔
$dom = new DomDocument();
//在根節(jié)點創(chuàng)建 departs標簽
$departs = $dom->createElement('departs');
$dom->appendChild($departs);
//在 departs標簽下創(chuàng)建 depart子標簽
$depart = $dom->createElement('depart');
$departs->appendChild($depart);
//在 depart標簽下創(chuàng)建 employees子標簽
$employees = $dom->createElement('employees');
$depart->appendChild($employees);
//在 employees標簽下創(chuàng)建 employee子標簽
$employee = $dom->createElement('employee');
$employees->appendChild($employee);
//在 employee標簽下創(chuàng)建 serial_no子標簽
$serial_no = $dom->createElement('serial_no');
$employee->appendChild($serial_no);
//為 serial_no標簽添加值節(jié)點 100001
$serial_no_value = $dom->createTextNode('100001′);
$serial_no->appendChild($serial_no_value);
//輸出 XML數(shù)據(jù)
echo $dom->saveXML();
?>
輸出結果如下所示。
<?xml version=”1.0″?>
<departs>
<depart>
<employees>
<employee>
<serial_no>100001</serial_no>
</employee>
</employees>
</depart>
</departs>
DOM組件除了可以用來動態(tài)創(chuàng)建 XML文檔外,還可以用來讀取 XML文件。以下代碼實現(xiàn)了對前 面 XML文件的讀取。
<?php
$dom = new DomDocument(); //創(chuàng)建 DOM對象
$dom->load('example.xml'); //讀取 XML文件
$root = $dom->documentElement; //獲取 XML數(shù)據(jù)的根
read_child($root); //調(diào)用 read_child函數(shù)讀取根對象
function read_child($node)
{
$children = $node->childNodes; //獲得$node的所有子節(jié)點
foreach($children as $e) //循環(huán)讀取每一個子節(jié)點
{
if($e->nodeType == XML_TEXT_NODE) //如果子節(jié)點為文本型則輸出
{
echo $e->nodeValue.”<BR>”;
}
else if($e->nodeType == XML_ELEMENT_NODE) //如果子節(jié)點為節(jié)點對象,則調(diào)用函數(shù)處理
{
read_child($e);
}
}
}
?>
運行結果如下所示。
引用
production support
100001
Simon
24
1982-11-06
5000.00
1000.00
100002
Elaine
24
1982-01-01
6000.00
2000.00
testing center
110001
Helen
23
1983-07-21
5000.00
1000.00
上面的例子使用了遞歸的方式對 XML數(shù)據(jù)進行了處理,實現(xiàn)了輸出 XML數(shù)據(jù)中的所有文本型標簽的功能。
4 XML應用實例——留言本
前面介紹了 XML的基本操作,本節(jié)將以設計一個 XML留言本為例來詳細說明在實際應用中如何實現(xiàn) PHP與 XML數(shù)據(jù)的交互操作。
4.1 XML文件結構設計
XML文件用于存儲 XML數(shù)據(jù),也就是留言本中的留言。這里,對于每條留言,在 XML數(shù)據(jù)中主要包括三項內(nèi)容:留言標題、留言者姓名、留言內(nèi)容。因此,將 XML文件的格式設計如下。
<?xml version=”1.0″?>
<threads>
<thread>
<title>這里是留言的標題</title>
<author>這里是留言者</author>
<content>這里是留言內(nèi)容</content>
</thread>
</threads>
4.2 提交頁面的編寫
提交留言頁面由兩個頁面組成。一個是讓訪問者用來書寫留言的表單的 HTML文件,一個是用來處理訪問者輸入的 PHP腳本。表單的 HTML代碼如下所示。
<html>
<head>
<title>發(fā)表新的留言</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″>
</head>
<body>
<H1><p align=”center”>發(fā)表新的留言</p></H1>
<form name=”form1″ method=”post” action=”Post.php”>
<table width=”500″ border=”0″ align=”center” cellpadding=”0″ cellspacing=”0″>
<tr>
<td>標題</td>
<td><input name=”title” type=”text” id=”title” size=”50″></td>
</tr>
<tr>
<td>作者</td>
<td><input name=”author” type=”text” id=”author” size=”20″></td>
</tr>
<tr>
<td>內(nèi)容</td>
<td><textarea name=”content” cols=”50″ rows=”10″ id=”content”></textarea></td>
</tr>
</table>
<p align=”center”>
<input type=”submit” value=”Submit”>
<input type=”reset” value=”Reset”>
</p>
</form>
</body>
</html>
對于用來處理用戶輸入的 PHP腳本,其基本邏輯是首先創(chuàng)建一個 DOM對象,然后讀取 XML文件中的 XML數(shù)據(jù),接下來在 XML對象上創(chuàng)建新的節(jié)點并將用戶的輸入儲存起來,最后將 XML數(shù)據(jù)輸出到原來的 XML文件中。具體實現(xiàn)代碼如下所示。
<?php
$guestbook = new DomDocument(); //創(chuàng)建一個新的 DOM對象
$guestbook->load('DB/guestbook.xml'); //讀取 XML數(shù)據(jù)
$threads = $guestbook->documentElement; //獲得 XML結構的根
//創(chuàng)建一個新 thread節(jié)點
$thread = $guestbook->createElement('thread');
$threads->appendChild($thread);
//在新的 thread節(jié)點上創(chuàng)建 title標簽
$title = $guestbook->createElement('title');
$title->appendChild($guestbook->createTextNode($_POST['title']));
$thread->appendChild($title);
//在新的 thread節(jié)點上創(chuàng)建 author標簽
$author = $guestbook->createElement('author');
$author->appendChild($guestbook->createTextNode($_POST['author']));
$thread->appendChild($author);
//在新的 thread節(jié)點上創(chuàng)建 content標簽
$content = $guestbook->createElement('content');
$content->appendChild($guestbook->createTextNode($_POST['content']));
$thread->appendChild($content);
//將 XML數(shù)據(jù)寫入文件
$fp = fopen(”DB/guestbook.xml”, “w”);
if(fwrite($fp, $guestbook->saveXML()))
echo “留言提交成功”;
else
echo “留言提交失敗”;
fclose($fp);
?>
在瀏覽器中運行上述 HTML文件并填寫適當?shù)牧粞詢?nèi)容,如圖 2所示。

圖 2 發(fā)表新留言界面
單擊【Submit】按鈕后,XML文件中的內(nèi)容如下所示。
可以看到 XML文件中已經(jīng)將留言存儲起來了。
4.3 顯示頁面的編寫
顯示頁面可以使用前面介紹的 SimpleXML組件很容易的實現(xiàn),具體實現(xiàn)代碼如下所示。
<?php
//打開用于存儲留言的 XML文件
$guestbook = simplexml_load_file('DB/guestbook.xml');
foreach($guestbook->thread as $th) //循環(huán)讀取 XML數(shù)據(jù)中的每一個 thread標簽
{
echo “<B>標題:</B>”.$th->title.”<BR>”;
echo “<B>作者:</B>”.$th->author.”<BR>”;
echo “<B>內(nèi)容:</B><PRE>”.$th->content.”
”;
echo “
”;
}
?>
在瀏覽器中查看運行結果如圖 3所示。?

更多PHP XML操作的各種方法解析(比較詳細)相關文章請關注PHP中文網(wǎng)!