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 我下载图形界面重启完就变成这样了,打字也打不了,动也动不了,该怎么解决(操作系统-centos)
  • ¥15 VBA中在窗体中遍历所有checkbox控件,提取出被选中的checkbox的caption值
  • ¥15 在Ubuntu上有什么命令,或者是系统文件能告诉我链接nvme ssd的pcie槽位是不是支持热插拔功能?
  • ¥15 ansys license许可证问题
  • ¥20 QQ号和密码都能正常登录微信 QQ号和密码登录微信显示密码错误
  • ¥15 qiankun主应用注册子应用提示跨域
  • ¥15 单片机RTOS Kernel与应用分离开发,Kernel如何调起应用?
  • ¥15 快手小店商家版APP怎么第三方APP跳转到指定用户聊天界面
  • ¥15 为什么AVL fire软件仿真时的步长改变了,仿真结果也会改变
  • ¥100 如何帮我写一个java小游戏