Dropdown list box using data from XML file

Build a select list from XML data

When XML values are inserted into HTML, escape the option value and visible label for the HTML output context.

<?php
$xml = simplexml_load_file('file-xml-demo.xml');
if ($xml !== false) {
    echo '<select name="student">';
    foreach ($xml->details as $student) {
        $id = htmlspecialchars((string) $student->id, ENT_QUOTES, 'UTF-8');
        $name = htmlspecialchars((string) $student->name, ENT_QUOTES, 'UTF-8');
        echo "<option value="$id">$name</option>";
    }
    echo '</select>';
}
?>

Current example first; the detailed examples below are retained for additional learning and comparison.

We can create one drop down list box by using data from our student table. This xml file is created by reading data from MySQL table. You can check the output as XML from our file-xml-demo.xml file.
Demo of dropdown list using XML data
Here is the PHP Script to generate the dropdown list
<?php
$obj_xml = new SimpleXMLElement('file-xml-demo.xml', NULL, TRUE);
// Total number of elements present ///
//$total = $obj_xml->count(); // total number of elements for PHP 5.3 and above
$total =count($obj_xml->children());  // for < php 5.3 version

$str="<select name='student'>";
for($i=0; $i<$total; $i++) { 
$str= $str . "<option value=".$obj_xml->details[$i]->id.">".$obj_xml->details[$i]->name. "</option>";
}
$str = $str. "</select>";
echo $str;
?>

XML XML Output from database records



Subscribe to our YouTube Channel here



plus2net.com







Schalk

09-11-2018

Ahhhhh, Yes. Thank you.This was exactly what I have been searching for. Thank you soooo much!




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer