How to Load or Read XML file using PHP
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Load or Read XML file using PHP</title>
</head>
<body>
<?php
//Read Specific XML Elements
$xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
echo $xmldata->employee[0]->firstname . "<br/>";
echo $xmldata->employee[1]->firstname . "<br/>";
echo $xmldata->employee[2]->firstname;
?><br/><br/>
<?php
//Read XML Elements In A Loop
$xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
foreach($xmldata->children() as $empl) {
echo $empl->firstname . ", ";
echo $empl->lastname . ", ";
echo $empl->designation . ", ";
echo $empl->salary . "<br/>";
}
?>
<br/><br/>
<?php
$xml = simplexml_load_file('xml/employee.xml');
echo '<h2>Employees Listing</h2>';
$list = $xml->employee;
for ($i = 0; $i < count($list); $i++) {
echo 'Name: ' . $list[$i]->firstname . '<br>';
echo 'Salary: ' . $list[$i]->salary . '<br>';
echo 'Position: ' . $list[$i]->designation . '<br><br>';
}
?>
</body>
</html>
//employee.xml
<?xml version="1.0"?>
<company>
<employee>
<firstname>Emma</firstname>
<lastname>Cruise</lastname>
<designation>MD</designation>
<salary>500000</salary>
</employee>
<employee>
<firstname>Olivia</firstname>
<lastname>Horne</lastname>
<designation>CEO</designation>
<salary>250000</salary>
</employee>
<employee>
<firstname>Isabella</firstname>
<lastname>Sophia</lastname>
<designation>Finance Manager</designation>
<salary>250000</salary>
</employee>
</company>
VIDEO