我无法使用简单的PHP解析器显示XML文件中的数据。我该如何解决?
我找不到这个简单任务的问题而且我完全陷入困境。我正在关注w3schools.com教程,代码不会显示数据。我在我的覆盆子pi上使用了一个apache web服务器。
PHP:
<html>
<head>
<style>
code {
font-family: ;
} div {
margin-top: 5px;
margin-bottom: 5px;
margin-left: 5px;
margin-right: 5px;
background-color: rgb(177,177,177);
height: 200px;
width: 300px;
}
</style>
</head>
<body>
<center><h1>Hello BISD! This is a perfectly fine webpage!</h1></center>
<p>TXT File:</p>
<div>
<?php
$file=fopen("placeholder.txt","r");
while(!feof($file)) {
echo fgets($file).'<br>';
}
fclose($file);
?>
</div>
<p>XML File:</p>
<div>
<?php
$XMLFile = simplexml_load_file("test.xml");
if ($XMLFile === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
foreach($XMLFile->message() as $data) {
echo $data->subject;
echo $data->recipient;
echo $data->sender;
}
}
?>
</div>
</body>
</html>
XML:
<?xml version='1.0' encoding='UTF-8'?>
<message>
<subject>Test XML File</subject>
<sender>Harry</sender>
<recipient>The Internet</recipient>
<content>Hello world!</content>
</message>
<message>
<subject>Regarding XML</subject>
<sender>Harry</sender>
<recipient>The Internet</recipient>
<content>XML is awesome!</content>
</message>
页面加载txt文件并显示正确。
答案 0 :(得分:3)
刚才说XML必须有1个根元素。而且,当你使用foreach构造时,你试图调用方法message(),而它是一个属性:
foreach($XMLFile->message as $data) {
echo $data->subject;
echo $data->recipient;
echo $data->sender;
}
答案 1 :(得分:2)
XML只能有1个根元素。见http://en.wikipedia.org/wiki/Root_element
您需要将XML更改为:
<?xml version='1.0' encoding='UTF-8'?>
<messages>
<message>
<subject>Test XML File</subject>
<sender>Harry</sender>
<recipient>The Internet</recipient>
<content>Hello world!</content>
</message>
<message>
<subject>Regarding XML</subject>
<sender>Harry</sender>
<recipient>The Internet</recipient>
<content>XML is awesome!</content>
</message>
</messages>