简体   繁体   中英

Using XML with PHP to return Data

I'm trying to echo a specific element's data from an XML file containing all the elements and their data. Here's my code:

$xml = simplexml_load_file("http://cslab.bc.edu/~cs254/data/periodic.xml");
$atom = $_GET['selectAtom'];
$symbol = $xml->$atom->SYMBOL;
echo $symbol;

The $atom variable returns the name of the atom after a user has submitted a form. I would like this php code to echo the symbol of the atom selected.

You can run XPath query to find it easily. Here's how:

$xml = simplexml_load_file("http://cslab.bc.edu/~cs254/data/periodic.xml");
$atom = 'Actinium';
$symbol = $xml->xpath("//ATOM[NAME='$atom']/SYMBOL");
echo $symbol[0];

Example in codepad .

尝试

$symbol = $xml->{$atom}->SYMBOL;

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