【问题标题】:Call to a member function createElement() on a non-object in php在 php 中调用非对象上的成员函数 createElement()
【发布时间】:2014-03-15 23:43:53
【问题描述】:

我想使用 XML DOM Parser 创建类似的 xml 文件

<dict>
<key>outlineThickness</key>     <real>0.0</real>
<key>repeat</key>       <false />
<key>rotation</key>     <string>no</string>
</dict>

但我的代码显示错误 注意:未定义变量:第 18 行 C:\wamp\www\iwatermark\xmlapi\xmlapi.php 中的 dom 致命错误:在第 18 行的 C:\wamp\www\iwatermark\xmlapi\xmlapi.php 中的非对象上调用成员函数 createElement()。

这是我写的

<?php

class XMLApi
{
    private $dom = null;
    private $root = null;
    public function __construct()
    {
        $dom = new DOMDocument("1.0");
        $dom->formatOutput = TRUE;

        $root = $dom->createElement("dict");
        $dom->appendChild($root);
    }

    public function createNode($keyname, $keytext, $valuename, $valuetext)
    {   
        $item = $dom->createElement($keyname);
        $root->appendChild($item);

        // create text node
        $text = $dom->createTextNode($keytext);
        $item->appendChild($text);

        if($valuename == "true" || $valuename == "false")
        {
            $item = $dom->createElement($valuename);
            $root->appendChild($item);
        }
        else
        {
            $item = $dom->createElement($valuename);
            $root->appendChild($item);

            // create text node
            $text = $dom->createTextNode($valuetext);
            $item->appendChild($text);
        }
        // create child element


    }

    public function ending()
    {
        $dom->save("test01.xml");
    }
}





$obj = new XMLApi();
$obj->createNode("key","outlineThickness","real","0.0");
$obj->createNode("key","repeat","false","");
$obj->createNode("key","rotation","string","no");
$obj->ending();




header("Location: "."test01.xml");

?>

【问题讨论】:

  • 在整个类中的 createNode 函数中使用 $this-&gt;dom 而不是 $dom

标签: php xml


【解决方案1】:

从类内部访问类变量时需要使用$this-&gt;dom

【讨论】:

  • 在这个 $item = this->dom->createElement($keyname) 上出现语法错误;
  • $this 不是this。在我们谈论 PHP 时,请注意 $,不是吗?
猜你喜欢
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 2015-09-19
  • 1970-01-01
相关资源
最近更新 更多