Luke Clynes Luke Clynes - 1 year ago 89
PHP Question

Pick random XML element - not working

I'm trying to use PHP to pick one random XML Element from a list of towns I have, but whenever I feel I might have fixed it, I get the same error.

I'm fairly new to PHP and have overcame many obstacles, but this is one I cannot figure out.

The error is:

Fatal error: Uncaught exception 'Exception' with message 'String could
not be parsed as XML' in
Stack trace: #0
SimpleXMLElement->__construct('towns.xml', 1, true) #1
include('/var/www/dev.we...') #2
require_once('/var/www/dev.we...') #3
require('/var/www/dev.we...') #4 {main} thrown in
on line 125

Here's the PHP code:

$towns = new SimpleXmlElement("towns.xml", 1, true);
$randomTown = array_rand($towns->xpath("ROW"));

<h3><?php echo $randomTown[0]->FIELD2 . ", " . $randomTown[0]->FIELD4; ?></h3>

Here's an example of the XML

<?xml version="1.0"?>
<FIELD2>Aaron&apos;s Hill</FIELD2>
<FIELD10>GU7 2</FIELD10>
<FIELD11>South East</FIELD11>
<FIELD12>Suburban Area</FIELD12>
<FIELD2>Abbas Combe</FIELD2>
<FIELD10>BA8 0</FIELD10>
<FIELD11>South West</FIELD11>

Answer Source

There are problems with using array_rand, because this function does not return array elements. It returns the index of a random array element. Try using this code:


$towns = new SimpleXmlElement("towns.xml", 1, true);
$rows = $towns->xpath("ROW");
$randomTown = array_rand($rows);

<h3><?php echo $rows[$randomTown]->FIELD2 . ", " .
               $rows[$randomTown]->FIELD4; ?></h3>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download