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) {
exit('Unable to load XML.');
}
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>';
?>
The examples below show additional XML structures, return values, and practical uses.
<?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;
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Schalk | 09-11-2018 |
| Ahhhhh, Yes. Thank you.This was exactly what I have been searching for. Thank you soooo much! | |