dp152153 2015-03-05 20:00
浏览 33
已采纳

PHP简单XML解析器不返回数据[重复]

This question already has an answer here:

I cannot display data from an XML file using the simple PHP parser. How do I fix it?

I cannot find the problem to this simple task and I am completely stuck. I am following a w3schools.com tutorial and the code won't display the data. I am using an apache web server on my raspberry pi.

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>

The page loads the txt file and displays it fine.

</div>
  • 写回答

2条回答 默认 最新

  • drvpvmz16241016 2015-03-05 22:19
    关注

    As just said XML must have 1 root element. Moreover, when you use the foreach construct, you are trying to call the method message(), while it's a property:

    foreach($XMLFile->message as $data) {
        echo $data->subject;
        echo $data->recipient;
        echo $data->sender;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死