PHP and XML

    XML (extensible markup language) works similarly to HTML with opening and closing tags. You can store and transfer data from one system to another using XML. You can create customized tags that are not possible in HTML. XML uses the DOM model to access and manipulate the XML data. The XML code can be converted to the XML DOM using XML parsers which can be manipulated using languages like javascript, python, and PHP.

    HTML (no closing li tags) XML (closing li tags)
    <ul>
    <li>text
    <li>text
    </ul>
    <ul>
    <li>text</li>
    <li>text</li>
    </ul>

    1. Parsing an XML document

    First, we will create a simple student.xml file.

    <?xml version="1.0" encoding="utf-8"?> // denoted the XML version
    <student status = "ok"> //root element
         <record man_no = "1">
             <name>Jacob Paul</name>
             <position>Manager</position>
         </record> //child element
         <record man_no = "2">
             <name>Tashu Smith</name>
             <position>Duty Manager</position>
            </record> //child element
    </student>

    2. Reading XML using PHP

    Below code list.php will read the student.xml file and displays the result on the web page.

    <?php
    //load the student.xml file and contents are assigned to $xml variable.
    $xml = simplexml_load_file('student.xml'); 
    echo '<h2>Students Listing</h2>';
    //get the content of record node.
    $stu_list = $xml->record;
    for ($i = 0; $i < count($stu_list); $i++) {
    echo '<b>Man no:</b> ' . $stu_list[$i]->attributes()->man_no . '<br>';
    echo 'Name: ' . $stu_list[$i]->name . '<br>';
    echo 'Position: ' . $stu_list[$i]->position . '<br><br>';
    }
    ?>

    3. Creating an XML document using PHP

    <?php    
        /* create a dom document with encoding utf8 */
        $domtree = new DOMDocument('1.0', 'UTF-8');
        /* create the root element of the xml tree */
        $xmlRoot = $domtree->createElement("xml");
        /* append it to the document created */
        $xmlRoot = $domtree->appendChild($xmlRoot);
        $currentTrack = $domtree->createElement("track");
        $currentTrack = $xmlRoot->appendChild($currentTrack);
        /* you should enclose the following two lines in a cicle */
        $currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
        $currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));
        $currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
        $currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));
        /* get the xml printed */
        echo $domtree->saveXML();
    ?>

    Output- As text-

    <?xml version="1.0" encoding="UTF-8"?>
    <xml><track><path>song1.mp3</path><title>title of song1.mp3</title><path>song2.mp3</path><title>title of song2.mp3</title></track></xml>

    As HTML-

    song1.mp3song2.mp3

    People are also reading: