Quantcast
Channel: Marius' Blog » PHP
Viewing all articles
Browse latest Browse all 5

How to parse a XML file using PHP

$
0
0

Here is an example on how to get data from XML files using PHP.

XML file example:

<?xml version="1.0" encoding="utf-8"?>
<Data>
    <Logo>Logo Test</Logo>
    <Title>Title Test</Title>
    <Subtitle>Subtitle Test</Subtitle>
    <Menu>
        <Item Name="Item 1" DataPath="DP Test" />
        <Item Name="Item 2" DataPath="DP Test" />
        <Item Name="Item 3">
            <Item Name="SubItem 1" DataPath="DP Test" />
            <Item Name="SubItem 2" DataPath="DP Test" />
            <Item Name="SubItem 3" DataPath="DP Test" />
            <Item Name="SubItem 4" DataPath="DP Test" />
            <Item Name="SubItem 5" DataPath="DP Test" />
        </Item>
        <Item Name="Item 4">
            <Item Name="SubItem 1" DataPath="DP Test" />
            <Item Name="SubItem 2" DataPath="DP Test" />
            <Item Name="SubItem 3" DataPath="DP Test" />
        </Item>
        <Item Name="Item 5" Type="T Test" DataPath="DP Test" />
    </Menu>
</Data>

PHP code:

$xmlDoc = new DOMDocument(); // Load a XML file.
$xmlDoc->load("menu.xml");
       
$XMLNode = $xmlDoc->documentElement;

//We go through all nodes from the XML and test their names. Depending on their names we take necessary actions.
foreach ($XMLNode->childNodes as $currentNode){
    if (strtolower($currentNode->nodeName) == "logo"){
        echo $currentNode->nodeValue."<br />"; // Read a node value.
    }
    if (strtolower($currentNode->nodeName) == "title"){
        echo $currentNode->nodeValue."<br />";
    }          
    if (strtolower($currentNode->nodeName) == "subtitle"){
        echo $currentNode->nodeValue."<br />";
    }          
    if (strtolower($currentNode->nodeName) == "menu"){
        foreach ($currentNode->childNodes as $menuItem){
            // Test if node has children.              
            if (strtolower($menuItem->nodeName) == "item" && $menuItem->hasChildNodes()){
                echo $menuItem->getAttribute(‘Name’)."<br />"; // Read a node attribute.
       
                foreach ($menuItem->childNodes as $submenuItem){
                    if (strtolower($submenuItem->nodeName) == "item"){
                        echo $submenuItem->getAttribute("Name");
                        echo $submenuItem->getAttribute("DataPath");
                    }                                  
                }
            }
            elseif (strtolower($menuItem->nodeName) == "item"){
                echo $menuItem->getAttribute("Name");
                echo $menuItem->getAttribute("DataPath");
            }  
        }
    }
}


Viewing all articles
Browse latest Browse all 5

Trending Articles