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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里