How to display XML data in web page using PHP ?

In this article, we are going to display data present in an XML file on a web page using PHP through the XAMPP server. PHP is a server-side scripting language that is mainly for processing web data. The XML stands for an extensible markup language.
Requirements:
-
XAMPP server
Syntax:
<root> <child> <subchild>.....</subchild> </child> </root>
Approach: We are going to use mainly two functions in our PHP code. The simplexml_load_file() function is used to convert an XML document to an object.
- simplexml_load_file
simplexml_load_file(name of XML file)
- children(): The children() function finds the children of a specified node.
$xml_data->children()
Steps to execute:
- Step 1: Start XAMPP server.
- Open notepad and type the following codes in xml_data.xml and code.php formats The xml_data.xml: Consider student XML data as an example.
xml_data.xml
<?xmlversion="1.0"encoding="utf-8"?><collegedata><departmentcategory="IT"><subjectslang="en">java</subjects><name>G.Sravan Kumar</name><age>22</age><marks>98</marks><address>guntur</address></department><departmentcategory="CSE"><subjectslang="en">Python</subjects><name>B. Naga sudheer</name><age>28</age><marks>96</marks><address>guntur</address></department><departmentcategory="IT"><subjectslang="en">sql</subjects><name>Radha</name><age>25</age><marks>78</marks><address>guntur</address></department></collegedata> -
Step 3:The following is the code for code.php file.
code.php
<?php// Start php code// Load xml file into xml_data variable$xml_data= simplexml_load_file("xml_data.xml")ordie("Error: Object Creation failure");// Use foreach loop to display data and for sub elements access,// We will use children() functionforeach($xml_data->children()as$data){//display each sub element in xml fileecho"Subject name : ",$data->subjects ."<br> ";echo"Student name : ",$data->name ."<br> ";echo"Student age : ",$data->age ."<br> ";echo"Student marks : ",$data->marks ."<br>";echo"Student address : ",$data->address ."<br>";echo"------------------------------------";echo"<br>";}?> - Step 4: Save these two files in xampp/htdocs/geek folder. The developer can use any other folder instead of geek folder.
Output: Open your browser and type localhost/geek/code.php to see the output.
XML data


