我正在尝试使用PHP从我所拥有的城镇列表中选择一个随机XML元素,但每当我觉得我可能已修复它时,我会得到同样的错误。
我对PHP很新,克服了许多障碍,但这是我无法弄清楚的。
错误是:
致命错误:未捕获的异常'异常',消息'字符串可以 不被解析为XML' /var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-content/themes/watchrepairs-2016/index.php:125 堆栈跟踪:#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}引入 /var/www/dev.weclarkwatchrepairs.co.uk/wordpress/wp-content/themes/watchrepairs-2016/index.php 在第125行
这是PHP代码:
$towns = new SimpleXmlElement("towns.xml", 1, true);
$randomTown = array_rand($towns->xpath("ROW"));
<h3><?php echo $randomTown[0]->FIELD2 . ", " . $randomTown[0]->FIELD4; ?></h3>
以下是XML
的示例<?xml version="1.0"?>
<ROWSET>
<ROW>
<FIELD1>1</FIELD1>
<FIELD2>Aaron'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>
答案 0 :(得分:0)
使用array_rand
时出现问题,因为此函数不返回数组元素。它返回随机数组元素的索引。尝试使用此代码:
<?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>