简体   繁体   中英

Load select option values from XML file

I would like to find a way to load select option values from a XML file. For example <option value="XXXXXX">XXXXXX</option> where the XXXXXX value is the <TITLE>XXXXXX</TITLE> of the following XML:

<?xml version="1.0" encoding="utf-8"?> 
<CATEGORIES> 
  <CD id="1">
    <TITLE>NEVER MIND THE BOLLOCKS</TITLE>
    <BAND>SEX PISTOLS</BAND>
    <YEAR>1977</YEAR>
  </CD>
  <CD id="2">
    <TITLE>NEVERMIND</TITLE>
    <BAND>NIRVANA</BAND>
    <YEAR>1991</YEAR>
  </CD>
</CATEGORIES>

Try this(haven't tested this):

$optionsXML = simplexml_load_file("OptionsList.xml"); //Replace OptionsList.xml with your file path.
$options =  $optionsXML->xpath("//TITLE/text()");
echo '<select name="test">';
while(list( $key , $value) = each($options)) {
    echo '<option >' . $value . '</option>';
}
echo '</select>';

EDIT: Updated the post to reflect the XML posted by OP.

Without knowing your xml structure, this is hard

$xml = simplexml_load_string('<names><name>1</name><name>2</name></names>');
echo '<select>';
foreach ($xml as $obj)
{
  echo '<option value="',(string)$obj, '">', (string)$obj, '</option>', "\n";
}
echo '</select>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM