在第7行调用非对象上的成员函数attributes()



好吧,伙计们,我到处都在寻找这个问题的答案,但没能解决这个问题。我创建了一个名为questions.xml的xml文档即

<Quiz>
    <topic text="Preparation for Exam">
        <subtopic text="Science">
            <question text="What is the largest planet in our solar system?"> 
            <answer num = "A" Text="Jupiter" correct="1"></answer> 
            <answer num = "B" Text="Venus" correct="0"></answer> 
            <answer num = "C" Text="Saturn" correct="0"></answer> 
            <answer num = "D" Text="Mars" correct="0"></answer> 
            </question>
            <question text="What is the smallest planet?" > 
            <answer num = "A" Text="Pluto" correct="1"></answer> 
            <answer num = "B" Text="Venus" correct="0"></answer> 
            <answer num = "C" Text="Saturn" correct="0"></answer> 
            <answer num = "D" Text="Mars" correct="0"></answer> 
            </question>
                </subtopic>
         </topic>
</Quiz> 

然后我制作了一个表格数据,显示不同的问题编号,我必须选择一个问题。我使用单选按钮进行选择,然后定义了一个名为"问题"的提交按钮。因此,当用户选择并提交任何问题时,单选按钮值0、1、2、3等将通过POST方法传递到另一个php页面。现在,在这个新的php页面中,我必须在文本字段区域中显示所需的问题。问题是,我总是收到这样一个愚蠢的错误"在第6行的非对象上调用成员函数attributes()"。我的代码是

<?php
    $condition= $_POST['question'];
    $xml = simplexml_load_file("questions.xml");
    echo $condition;
    if ($condition=="0"){
        $question= $xml-> topic -> subtopic-> question[$condition] ->  attributes()-> text."<br>";
        echo "<form action='' method='post'> 
        <label for='question'> Question</label>
        <textarea name='question' id='1' cols='45' rows='5'>".$question."</textarea>
        <P><INPUT TYPE=SUBMIT VALUE='submit'> </form>";
        }
 ?>

现在没有语法错误,程序显示echo$condition,但不显示问题始终显示"在第6行的非对象上调用成员函数attributes()"。我真的很生气。。请帮帮我。

$xml-> topic -> subtopic-> question[0]存在,而$xml-> topic -> subtopic-> question["0"]不存在。

$_POST['question']转换为integer即可。

$condition= (int) $_POST['question'];

会起作用。

首先检查,您收到一个用户输入,因此它可以不设置,也可以是任何字符串。

强制转换为int:

$condition = (isset($_POST['question'])) ? (int) $_POST['question'] : "some default value" ;
if (isset($xml-> topic -> subtopic-> question[$condition]) && is_object($xml-> topic -> subtopic-> question[$condition])){
  $question= $xml-> topic -> subtopic-> question[$condition] ->  attributes()-> text."<br/">
  //and so on.
}

最新更新