Luke Clynes Luke Clynes - 8 days ago 6
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
/var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-content/themes/watchrepairs-2016/index.php:125
Stack trace: #0
/var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-content/themes/watchrepairs-2016/index.php(125):
SimpleXMLElement->__construct('towns.xml', 1, true) #1
/var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-includes/template-loader.php(75):
include('/var/www/dev.we...') #2
/var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-blog-header.php(19):
require_once('/var/www/dev.we...') #3
/var/www/dev.weclarkwatchrepairs.co.uk/wordpress/index.php(17):
require('/var/www/dev.we...') #4 {main} thrown in
/var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-content/themes/watchrepairs-2016/index.php
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"?>
<ROWSET>
<ROW>
<FIELD1>1</FIELD1>
<FIELD2>Aaron&apos;s Hill</FIELD2>
<FIELD3>Surrey</FIELD3>
<FIELD4>England</FIELD4>
<FIELD5>SU957435</FIELD5>
<FIELD6>495783</FIELD6>
<FIELD7>143522</FIELD7>
<FIELD8>51.18291</FIELD8>
<FIELD9>-0.63098</FIELD9>
<FIELD10>GU7 2</FIELD10>
<FIELD11>South East</FIELD11>
<FIELD12>Suburban Area</FIELD12>
</ROW>
<ROW>
<FIELD1>2</FIELD1>
<FIELD2>Abbas Combe</FIELD2>
<FIELD3>Somerset</FIELD3>
<FIELD4>England</FIELD4>
<FIELD5>ST707226</FIELD5>
<FIELD6>370749</FIELD6>
<FIELD7>122688</FIELD7>
<FIELD8>51.00283</FIELD8>
<FIELD9>-2.41825</FIELD9>
<FIELD10>BA8 0</FIELD10>
<FIELD11>South West</FIELD11>
<FIELD12>Village</FIELD12>
</ROW>
</ROWSET>

Answer

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:

<?php

$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>