How to Extract XML Tags With PHP
The PHP language provides support for Extensible Markup Language (XML) file interfacing. XML is a file format designed with data interchange in mind. XML files are frequently used to transfer data across the Internet. The PHP language takes full advantage of the XML language. If you are new to either PHP or XML, you can start learning about them both by finding out how to extract XML tags from an XML file. This takes only a few lines of code and serves as a decent introduction to XML parsing in PHP.
Instructions
-
-
1
Create a simple XML file by opening up a text editor like wordpad.exe and saving the file as "simple.xml." XML files are designed as hierarchies of nodes. A node connected below another node is called a child node. A node is designated by writing an XML tag using angle braces (< and >).You can create a simple hierarchy of nodes by writing the following within the XML file:
<?xml version="1.0"?>
<rootNode>
<childNode1>Text for childNode1</childNode1>
<childNode2>Text for childNode2</childNode2>
</rootNote>
-
2
Decide how you will run your PHP code. If you have a PHP server, you can execute code using PHP files. If you do not have access to a PHP server, you can use an online PHP interpreter. Enter the code in this tutorial into either a PHP file or the online PHP interpreter.
-
-
3
Begin your PHP program with the following statement:
<?php
-
4
Load an xml file using the PHP function "simplexml_load_file." For example, to load an XML file named "simple.xml," write the following line of code:
$xmlFile = simplexml_load_file("simple.xml");
-
5
Iterate through the XML file using a foreach loop. By iterating over all of the child nodes of the XML file, you can visit each one and view its tag. To iterate over all of the child nodes, write the following statements:
foreach ($xmlFile->children() as $current) {}
-
6
Print out the XML tag located in the currently visited node in the XML file. You can accomplish this by writing the following statement within the curly brackets of the foreach loop:
echo "XML Tag: " . $current->getName() "<br />";
-
7
Conclude your PHP program with the statement below. Your program is now ready to be tested on your PHP server or online PHP interpreter.
?>
-
8
Observe the output of the PHP program. The program iterates over the nodes of the XML file and prints out the tag names. The output looks like this:
XML Tag: rootNode
XML Tag: childNode1
XML Tag: childNode2
-
1