Home > Backend Development > PHP Tutorial > Detailed explanation of php operation xml_PHP tutorial

Detailed explanation of php operation xml_PHP tutorial

WBOY
Release: 2016-07-15 13:21:47
Original
1112 people have browsed it

XML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple and low-security data are often stored in XML file format. The advantage of this is that on the one hand, it can improve reading efficiency by reducing interactive operations with the database, and on the other hand, it can effectively utilize the advantages of XML to reduce the difficulty of program writing.​

PHP provides a complete set of methods for reading XML files, making it easy to write XML-based scripts. This chapter will introduce the operation methods of PHP and XML, and give a brief introduction to several commonly used XML class libraries.
1 Introduction to XML
XML is the abbreviation of "eXtensible Markup Language" and is a markup language similar to HTML. But unlike HTML, XML is mainly used to describe data and store data, while HTML is mainly used to display data.
XML is a "meta tag" language that allows developers to create tag names according to their needs. For example, the following XML code can be used to describe a message.
Copy the code The code is as follows:
Welcome
Simon
Welcome to XML guestbook!!
Among them, the and tags mark this as a message. There is a title, author, and content in the message, which completely expresses a message message.
At the top of an XML file, is usually used to identify the beginning of XML data and XML data uses standard version information. When you access an XML file in a browser, you can see clearly structured XML data information, as shown in Figure 1.
XML is developing very rapidly. In recent years, many software developers have begun to adopt XML development standards for application development. Moreover, many emerging technologies are built on XML data. This means that XML will become as integral a part of Web technology as HTML.
2 Simple XML operations
In practical applications, the interaction between PHP and XML is widely used. SimpleXML component is a new simple addition to PHP5
A single XML operation component. Compared with traditional XML components, the use of SimpleXML components is very simple. This section will explain how to use
The SimpleXML component’s method of manipulating XML will be introduced in detail.
2.1 Create a SimpleXML object
SimpleXML object is a temporary variable used to temporarily store XML data. Operations on XML are completed by operating SimpleXML objects. The SimpleXML component provides two methods for creating SimpleXML objects. The first method is to use the simplexml_load_string function to read the XML data in a string variable to complete the creation. The syntax format is as follows.
simplexml_load_string(string data)
The data variable here is used to store XML data. The following code creates a SimpleXML object using the simplexml_load_string function
Copy the code The code is as follows:
$data = <<
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;
$xml = simplexml_load_string($data); //Create SimpleXML object
print_r($xml); //Output XML
?>
In the above example, the $data variable stores a piece of XML data. The simplexml_load_string function converts the variable $data into a SimpleXML object. The structure of the object can be seen through the output of the print_r function, and the running results are as follows.
Copy the code The code is as follows:
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
)
)
)
)
)
As can be seen from the output results, the structure of the SimpleXML object is exactly the same as the format of the XML data.
The second method is to use the simplexml_load_flie function to read an XML file to complete the creation. The syntax format is as follows.
simplexml_load_file(string filename)
The filename variable here is the file name and path used to store the XML data file. The following code uses the simplexml_load_file function to create a SimpleXML object.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Create SimpleXML object
print_r($xml); //Output XML
?>
Among them, the data stored in example.xml is exactly the same as the $data above, and the running results are exactly the same as above.
The above two methods implement the same function, the difference lies in the different data sources of XML. If the XML data source is in a PHP script file, you need to use simplexml_load_string to create it. If the XML data source is in a separate XML file, you need to use simplexml_load_file to create it.
2.2 Read XML data in SimpleXML object
Previously we introduced the use of the print_r function to read data in a SimpleXML object, and its return result is similar to the structure of an array. Obviously, this display method is undesirable in practical applications. Here we will introduce several other methods of reading XML data in SimpleXML objects.
1. The var_dump function displays object details
The var_dump function can be used to display detailed information of SimpleXML objects. Compared with the print_r function, the var_dump function displays more complete information. Its syntax is as follows.
void var_dump(object1, object2 … )
The following code uses the var_dump function to output detailed information about the object in the above example.
Copy the code The code is as follows:
The running results are as follows.
Copy the code The code is as follows:
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函数的输出结果的结构更为严谨,并且将对象中的每一个属性的数据类型均作出分析。在实际应用中,var_dump函数往往用于程序调试时的对象检测。 
2.读取 XML数据中的标签 
与操作数组类型的变量类似,读取 XML也可以通过类似的方法来完成。例如,如果需要读取上面 XML数据中每一个“ depart”标签下的“name”属性,可以通过使用 foreach函数来完成,如以下代码 
所示。 
复制代码 代码如下:
depart as $a) 
echo “$a->name
”; 
?> 
 
运行结果如下所示。 
production support 
testing center 
//读取 XML文件 //循环读取 XML数据中的每一个 depart标签 
//输出其中的 name属性 
也可以使用方括号“ []”来直接读取 XML数据中指定的标签。以下代码输出了上面 XML数据中的第一个“depart”标签的“name”属性。 
复制代码 代码如下:
$xml = simplexml_load_file('example.xml'); //读取 XML文件 
echo $xml->depart->name[0]; //输出节点 
?> 
 
运行结果如下所示。 
production support 
对于一个标签下的所有子标签,SimpleXML组件提供了 children方法进行读取。例如,对于上面的 XML数据中的“ depart”标签,其下包括两个子标签:“ name”和“employees”。以下代码实现了对第一个“depart”标签下的子标签的读取。 
复制代码 代码如下:
$xml = simplexml_load_file('example.xml');
foreach ($xml->depart->children() as $depart) //Loop to read the sub-tags under the depart tag
{
var_dump($depart); //Output the XML data of the tag
}
?>
The running results are as follows.
Copy the code The code is as follows:
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″
}
}
}
It can be seen that after using the children method, all child tags are treated as a new XML file.
3. Query based on XML data path
SimpleXML component provides a query method based on XML data path. The XML data path is all the tags that pass from the root of XML to a certain tag. This path uses slashes "/" to separate tag names. For example, for the above XML data, if you want to query the values ​​​​in all tags "name", starting from the root and going through the departs, department, employees and employee tags, the path is
is "/departs/depart/employees/employee/name". The SimpleXML component uses the xpath method to parse paths, and its syntax format is as follows.
xpath(string path)
The path is the path. This method returns an array containing all tag values ​​to be queried. The following code queries all name tags in the above XML data.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML file
$result = $xml->xpath('/departs/depart/employees/employee/name'); //Define node
var_dump($result); //Output node
?>
The running results are as follows.
Copy the code The code is as follows:
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”
}
}
It can be seen that all name tags have been queried.
2.3 Modification of XML data
The modification of XML data is similar to the method of reading tags in XML data. That is, by directly modifying the value of the tag in the SimpleXML object. The following code implements the modification of the "name" sub-tag of the first "depart" tag in the XML data above.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML
$xml->depart->name[0] = “Human Resource”; //Modify node
?>
After modification, it will not have any impact on the XML file. However, in the program, the modified value will be used for reading the SimpleXML object.
2.4 Standardized XML data
SimpleXML also provides a way to standardize XML data asXML. The asXML method can effectively rearrange the content in the SimpleXML object according to the XML 1.0 standard and return it as a string data type. The following code implements the standardization of the above XML data.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML data
echo $xml->asXML(); //Standardized XML data
?>
2.5 Storage of XML data
The method of storing XML data in a SimpleXML object into an XML file is very simple, that is, outputting the return result of the asXML method to a file. The following code first modifies the depart name in the XML file, and then outputs the modified XML data to another XML file.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML data
$newxml = $xml->asXML(); //Standardized XML data
$fp = fopen(”newxml.xml”, “w”); //Open the file to write XML data
fwrite($fp, $newxml); //Write XML data
fclose($fp); //Close the file
?>
After the code is run, you can see that the XML data in the newxml.xml file is as follows.
It can be seen that the modifications to the XML file have been saved in the output file.
3 Dynamic creation of XML documents
In practical applications, it is sometimes necessary to dynamically generate XML documents. The SimpleXML component introduced earlier does not provide a method for creating XML documents. Therefore, if you need to dynamically create an XML document, you often use DOM components to create it. DOM is the abbreviation of Document Object Model. The DOM component provides a tree parsing mode for XML documents. The following code creates an XML document using DOM components.
Copy the code The code is as follows:
//Create a new DOM document
$dom = new DomDocument();
//Create the departs label at the root node
$departs = $dom->createElement('departs');
$dom->appendChild($departs);
//Create the depart sub-tag under the departs tag
$depart = $dom->createElement('depart');
$departs->appendChild($depart);
//Create employees sub-tag under the depart tag
$employees = $dom->createElement('employees');
$depart->appendChild($employees);
//Create employee sub-tag under employees tag
$employee = $dom->createElement('employee');
$employees->appendChild($employee);
//Create serial_no sub-tag under employee tag
$serial_no = $dom->createElement('serial_no');
$employee->appendChild($serial_no);
//Add value node 100001 for serial_no tag
$serial_no_value = $dom->createTextNode('100001′);
$serial_no->appendChild($serial_no_value);
//Output XML data
echo $dom->saveXML();
?>
The output results are shown below.
100001
In addition to being used to dynamically create XML documents, the DOM component can also be used to read XML files. The following code implements the front
Reading of XML files.
Copy the code The code is as follows:
$dom = new DomDocument(); //Create DOM object
$dom->load('example.xml'); //Read XML file
$root = $dom->documentElement; //Get the root of XML data
read_child($root); //Call the read_child function to read the root object
function read_child($node)
{
$children = $node->childNodes; //Get all child nodes of $node
foreach($children as $e) //Loop to read each child node
{
if($e->nodeType == XML_TEXT_NODE) ​​//If the child node is text type, output
{
echo $e->nodeValue.”
”;
}
else if($e->nodeType == XML_ELEMENT_NODE) ​​//If the child node is a node object, call the function processing
{
read_child($e);
}
}
}
?>
The running results are as follows.
Copy the code The code is as follows:
Quote
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
The above example uses a recursive method to process XML data and realizes the function of outputting all text tags in XML data.
4 XML application examples - Guestbook
The basic operations of XML have been introduced before. This section will take designing an XML guestbook as an example to explain in detail how to realize the interaction between PHP and XML data in practical applications.
4.1 XML file structure design
XML files are used to store XML data, which are the messages in the guestbook. Here, for each message, the XML data mainly includes three contents: message title, message author's name, and message content. Therefore, the format of the XML file is designed as follows.
Copy the code The code is as follows:
Here is the title of the message
This is the commenter
Here is the content of the message
4.2 Writing the submission page
The message submission page consists of two pages. One is an HTML file for a form that allows visitors to write messages, and the other is a PHP script used to process visitor input. The HTML code for the form is shown below.
Copy the code The code is as follows:
Post a new comment

Post a new message

Title
Author
Content

For PHP scripts used to process user input, the basic logic is to first create a DOM object, then read the XML data in the XML file, and then create new nodes on the XML object and store the user's input , and finally output the XML data to the original XML file. The specific implementation code is as follows.
Copy the code The code is as follows:
$guestbook = new DomDocument(); //Create a new DOM object
$guestbook->load('DB/guestbook.xml'); //Read XML data
$threads = $guestbook->documentElement; //Get the root of the XML structure
//Create a new thread node
$thread = $guestbook->createElement('thread');
$threads->appendChild($thread);
//Create title tag on the new thread node
$title = $guestbook->createElement('title');
$title->appendChild($guestbook->createTextNode($_POST['title']));
$thread->appendChild($title);
//Create author tag on the new thread node
$author = $guestbook->createElement('author');
$author->appendChild($guestbook->createTextNode($_POST['author']));
$thread->appendChild($author);
//Create content tag on the new thread node
$content = $guestbook->createElement('content');
$content->appendChild($guestbook->createTextNode($_POST['content']));
$thread->appendChild($content);
//Write XML data to file
$fp = fopen("DB/guestbook.xml", "w");
if(fwrite($fp, $guestbook->saveXML()))
echo “Message submitted successfully”;
else
echo “Message submission failed”;
fclose($fp);
?>
Run the above HTML file in the browser and fill in the appropriate message content, as shown in Figure 2.
Figure 2 New message posting interface
After clicking the [Submit] button, the content in the XML file is as follows.
You can see that the message has been stored in the XML file.
4.3 Writing the display page
The display page can be easily implemented using the SimpleXML component introduced earlier. The specific implementation code is as follows.
Copy the code The code is as follows:
//Open the XML file used to store messages
$guestbook = simplexml_load_file('DB/guestbook.xml');
foreach($guestbook->thread as $th) //Loop to read each thread tag in the XML data
{
echo “Title:”.$th->title.”
”;
echo “Author:”.$th->author.”
”;
echo “Content:
”.$th->content.”
”;
echo “
”;
}
?>
View the running results in the browser as shown in Figure 3.
Articles you may be interested in:
PHP code for reading XML values ​​(recommended)
php reads xml example code
Several ways to write and read XML with PHP
Sharing 4 ways to generate XML files in PHP
Implementation code for reading and writing XML DOM with PHP
Instructions for using the simplexml_load_string function in PHP
php xml introductory learning materials
PHP operates XML as a database class
php generates xml simple example code
The implementation code of combining php with XML, XSLT and Mysql
The XML generated by PHP is obtained by FLASH as the ultimate solution to garbled characters
Introduction to PHP reading xml method
Detailed source reference: http://www.jb51.net/article/23912.htmXML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple and low-security data are often stored in XML file format. The advantage of this is that on the one hand, it can improve reading efficiency by reducing interactive operations with the database, and on the other hand, it can effectively utilize the advantages of XML to reduce the difficulty of program writing.
PHP provides a complete set of methods for reading XML files, making it easy to write XML-based scripts. This chapter will introduce the operation methods of PHP and XML, and give a brief introduction to several commonly used XML class libraries.
1 Introduction to XML
XML是“可扩展性标识语言(eXtensible Markup Language)”的缩写,是一种类似于 HTML的标记性语言。但是与 HTML不同,XML主要用于描述数据和存放数据,而 HTML主要用于显示数据。 
XML是一种“元标记”语言,开发者可以根据自己的需要创建标记的名称。例如,下面的 XML代码可以用来描述一条留言。 
 
 
复制代码 代码如下:
 
Welcome 
Simon 
Welcome to XML guestbook!! 
 
 
其中,标签标记了这是一段留言。在留言中有标题、作者、内容,完整的表述了一条留言信息。 
在一个 XML文件的顶部,通常使用来标识 XML数据的开始和 XML数据使用标准的版本信息。在浏览器中访问 XML文件可以看到层次分明的 XML数据信息,如图 1所示。 
 
XML的发展非常迅速,近些年来很多软件开发商都开始采用 XML的开发标准进行应用程序的开发。并且,很多新兴技术都架构在 XML数据之上。这意味着 XML将与 HTML一样成为 Web技术不可或缺的一部分。 
2 简单的 XML操作 
在实际应用中,PHP与 XML的交互操作应用非常广泛。SimpleXML组件是 PHP5新增加的一个简 
单的 XML操作组件,与传统的 XML组件相比,SimpleXML组件的使用非常简单。本节将对使用 
SimpleXML组件操作 XML的方法做一下详细介绍。 
2.1 创建一个 SimpleXML对象 
SimpleXML对象是用来临时存储 XML数据的临时变量,对 XML进行的操作都是通过操作 SimpleXML对象来完成的。SimpleXML组件提供了两种创建 SimpleXML对象的方法。第一种方法是使用 simplexml_load_string函数读取一个字符串型变量中的 XML数据来完成创建的,其语法格式如下所示。 
simplexml_load_string(string data) 
这里的 data变量用于存储 XML数据。以下代码使用 simplexml_load_string函数创建了一个 SimpleXML对象 
复制代码 代码如下:
$data = <<
 
 
 
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;
$xml = simplexml_load_string($data); //Create SimpleXML object
print_r($xml); //Output XML
?>
In the above example, the $data variable stores a piece of XML data. The simplexml_load_string function converts the variable $data into a SimpleXML object. The structure of the object can be seen through the output of the print_r function, and the running results are as follows.
Copy the code The code is as follows:
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
)
)
)
)
)
As can be seen from the output results, the structure of the SimpleXML object is exactly the same as the format of the XML data.
The second method is to use the simplexml_load_flie function to read an XML file to complete the creation. The syntax format is as follows.
simplexml_load_file(string filename)
The filename variable here is the file name and path used to store the XML data file. The following code uses the simplexml_load_file function to create a SimpleXML object.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Create SimpleXML object
print_r($xml); //Output XML
?>
Among them, the data stored in example.xml is exactly the same as the $data above, and the running results are exactly the same as above.
The above two methods implement the same function, the difference lies in the different data sources of XML. If the XML data source is in a PHP script file, you need to use simplexml_load_string to create it. If the XML data source is in a separate XML file, you need to use simplexml_load_file to create it.
2.2 Read XML data in SimpleXML object
Previously we introduced the use of the print_r function to read data in a SimpleXML object, and its return result is similar to the structure of an array. Obviously, this display method is undesirable in practical applications. Here we will introduce several other methods of reading XML data in SimpleXML objects.
1. The var_dump function displays object details
The var_dump function can be used to display detailed information of SimpleXML objects. Compared with the print_r function, the var_dump function displays more complete information. Its syntax is as follows.
void var_dump(object1, object2 … )
The following code uses the var_dump function to output detailed information about the object in the above example.
Copy the code The code is as follows:
The running results are as follows.
Copy the code The code is as follows:
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函数的输出结果的结构更为严谨,并且将对象中的每一个属性的数据类型均作出分析。在实际应用中,var_dump函数往往用于程序调试时的对象检测。 
2.读取 XML数据中的标签 
与操作数组类型的变量类似,读取 XML也可以通过类似的方法来完成。例如,如果需要读取上面 XML数据中每一个“ depart”标签下的“name”属性,可以通过使用 foreach函数来完成,如以下代码 
所示。 
复制代码 代码如下:
depart as $a) 
echo “$a->name
”; 
?> 
 
运行结果如下所示。 
production support 
testing center 
//读取 XML文件 //循环读取 XML数据中的每一个 depart标签 
//输出其中的 name属性 
也可以使用方括号“ []”来直接读取 XML数据中指定的标签。以下代码输出了上面 XML数据中的第一个“depart”标签的“name”属性。 
复制代码 代码如下:
$xml = simplexml_load_file('example.xml'); //读取 XML文件 
echo $xml->depart->name[0]; //输出节点 
?> 
 
运行结果如下所示。 
production support 
对于一个标签下的所有子标签,SimpleXML组件提供了 children方法进行读取。例如,对于上面的 XML数据中的“ depart”标签,其下包括两个子标签:“ name”和“employees”。以下代码实现了对第一个“depart”标签下的子标签的读取。 
复制代码 代码如下:
$xml = simplexml_load_file('example.xml');
foreach ($xml->depart->children() as $depart) //Loop to read the sub-tags under the depart tag
{
var_dump($depart); //Output the XML data of the tag
}
?>
The running results are as follows.
Copy the code The code is as follows:
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″
}
}
}
It can be seen that after using the children method, all child tags are treated as a new XML file.
3. Query based on XML data path
SimpleXML component provides a query method based on XML data path. The XML data path is all the tags that pass from the root of XML to a certain tag. This path uses slashes "/" to separate tag names. For example, for the above XML data, if you want to query the values ​​​​in all tags "name", starting from the root and going through the departs, department, employees and employee tags, the path is
is "/departs/depart/employees/employee/name". The SimpleXML component uses the xpath method to parse paths, and its syntax format is as follows.
xpath(string path)
The path is the path. This method returns an array containing all tag values ​​to be queried. The following code queries all name tags in the above XML data.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML file
$result = $xml->xpath('/departs/depart/employees/employee/name'); //Define node
var_dump($result); //Output node
?>
The running results are as follows.
Copy the code The code is as follows:
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”
}
}
It can be seen that all name tags have been queried.
2.3 Modification of XML data
The modification of XML data is similar to the method of reading tags in XML data. That is, by directly modifying the value of the tag in the SimpleXML object. The following code implements the modification of the "name" sub-tag of the first "depart" tag in the XML data above.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML
$xml->depart->name[0] = “Human Resource”; //Modify node
?>
After modification, it will not have any impact on the XML file. However, in the program, the modified value will be used for reading the SimpleXML object.
2.4 Standardized XML data
SimpleXML also provides a way to standardize XML data asXML. The asXML method can effectively rearrange the content in the SimpleXML object according to the XML 1.0 standard and return it as a string data type. The following code implements the standardization of the above XML data.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML data
echo $xml->asXML(); //Standardized XML data
?>
2.5 Storage of XML data
The method of storing XML data in a SimpleXML object into an XML file is very simple, that is, outputting the return result of the asXML method to a file. The following code first modifies the depart name in the XML file, and then outputs the modified XML data to another XML file.
Copy the code The code is as follows:
$xml = simplexml_load_file('example.xml'); //Read XML data
$newxml = $xml->asXML(); //Standardized XML data
$fp = fopen(”newxml.xml”, “w”); //Open the file to write XML data
fwrite($fp, $newxml); //Write XML data
fclose($fp); //Close the file
?>
After the code is run, you can see that the XML data in the newxml.xml file is as follows.
It can be seen that the modifications to the XML file have been saved in the output file.
3 Dynamic creation of XML documents
In practical applications, it is sometimes necessary to dynamically generate XML documents. The SimpleXML component introduced earlier does not provide a method for creating XML documents. Therefore, if you need to dynamically create an XML document, you often use DOM components to create it. DOM is the abbreviation of Document Object Model. The DOM component provides a tree parsing mode for XML documents. The following code creates an XML document using DOM components.
Copy the code The code is as follows:
//Create a new DOM document
$dom = new DomDocument();
//Create the departs label at the root node
$departs = $dom->createElement('departs');
$dom->appendChild($departs);
//Create the depart sub-tag under the departs tag
$depart = $dom->createElement('depart');
$departs->appendChild($depart);
//Create employees sub-tag under the depart tag
$employees = $dom->createElement('employees');
$depart->appendChild($employees);
//Create employee sub-tag under employees tag
$employee = $dom->createElement('employee');
$employees->appendChild($employee);
//Create serial_no sub-tag under employee tag
$serial_no = $dom->createElement('serial_no');
$employee->appendChild($serial_no);
//Add value node 100001 for serial_no tag
$serial_no_value = $dom->createTextNode('100001′);
$serial_no->appendChild($serial_no_value);
//Output XML data
echo $dom->saveXML();
?>
The output results are shown below.
100001
In addition to being used to dynamically create XML documents, the DOM component can also be used to read XML files. The following code implements the front
Reading of XML files.
Copy the code The code is as follows:
$dom = new DomDocument(); //Create DOM object
$dom->load('example.xml'); //Read XML file
$root = $dom->documentElement; //Get the root of XML data
read_child($root); //Call the read_child function to read the root object
function read_child($node)
{
$children = $node->childNodes; //Get all child nodes of $node
foreach($children as $e) //Loop to read each child node
{
if($e->nodeType == XML_TEXT_NODE) ​​//If the child node is text type, output
{
echo $e->nodeValue.”
”;
}
else if($e->nodeType == XML_ELEMENT_NODE) ​​//If the child node is a node object, call the function processing
{
read_child($e);
}
}
}
?>
The running results are as follows.
Copy the code The code is as follows:
Quote
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
The above example uses a recursive method to process XML data and realizes the function of outputting all text tags in XML data.
4 XML application examples - Guestbook
The basic operations of XML have been introduced before. This section will take designing an XML guestbook as an example to explain in detail how to realize the interaction between PHP and XML data in practical applications.
4.1 XML file structure design
XML files are used to store XML data, which are the messages in the guestbook. Here, for each message, the XML data mainly includes three contents: message title, message author's name, and message content. Therefore, the format of the XML file is designed as follows.
Copy the code The code is as follows:
Here is the title of the message
This is the commenter
Here is the content of the message
4.2 Writing the submission page
The message submission page consists of two pages. One is an HTML file for a form that allows visitors to write messages, and the other is a PHP script used to process visitor input. The HTML code for the form is shown below.
Copy the code The code is as follows:
Post a new comment

Post a new message

Title
Author
Content

对于用来处理用户输入的 PHP脚本,其基本逻辑是首先创建一个 DOM对象,然后读取 XML文件中的 XML数据,接下来在 XML对象上创建新的节点并将用户的输入储存起来,最后将 XML数据输出到原来的 XML文件中。具体实现代码如下所示。 
复制代码 代码如下:
$guestbook = new DomDocument(); //创建一个新的 DOM对象
$guestbook->load('DB/guestbook.xml'); //读取 XML数据 
$threads = $guestbook->documentElement; //获得 XML结构的根 
//创建一个新 thread节点 
$thread = $guestbook->createElement('thread'); 
$threads->appendChild($thread); 
//在新的 thread节点上创建 title标签 
$title = $guestbook->createElement('title');
$title->appendChild($guestbook->createTextNode($_POST['title']));
$thread->appendChild($title);
//Create author tag on the new thread node
$author = $guestbook->createElement('author');
$author->appendChild($guestbook->createTextNode($_POST['author']));
$thread->appendChild($author);
//Create content tag on the new thread node
$content = $guestbook->createElement('content');
$content->appendChild($guestbook->createTextNode($_POST['content']));
$thread->appendChild($content);
//Write XML data to file
$fp = fopen("DB/guestbook.xml", "w");
if(fwrite($fp, $guestbook->saveXML()))
echo “Message submitted successfully”;
else
echo “Message submission failed”;
fclose($fp);
?>
Run the above HTML file in the browser and fill in the appropriate message content, as shown in Figure 2.
Figure 2 New message posting interface
After clicking the [Submit] button, the content in the XML file is as follows.
You can see that the message has been stored in the XML file.
4.3 Writing the display page
The display page can be easily implemented using the SimpleXML component introduced earlier. The specific implementation code is as follows.
Copy the code The code is as follows:
//Open the XML file used to store messages
$guestbook = simplexml_load_file('DB/guestbook.xml');
foreach($guestbook->thread as $th) //Loop to read each thread tag in the XML data
{
echo “Title:”.$th->title.”
”;
echo “Author:”.$th->author.”
”;
echo “Content:
”.$th->content.”
”;
echo “
”;
}
?>
View the running results in the browser as shown in Figure 3.
Articles you may be interested in:
PHP code for reading XML values ​​(recommended)
php reads xml example code
Several ways to write and read XML with PHP
Sharing 4 ways to generate XML files in PHP
Implementation code for reading and writing XML DOM with PHP
Instructions for using the simplexml_load_string function in PHP
php xml introductory learning materials
PHP operates XML as a database class
php generates xml simple example code
The implementation code of combining php with XML, XSLT and Mysql
The XML generated by PHP is obtained by FLASH as the ultimate solution to garbled characters
Introduction to PHP reading xml method

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477139.htmlTechArticleXML is a popular semi-structured file format that stores data in a database-like format. In practical applications, some simple and low-security data often use XML files...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template