Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于PHP5.x通过dom创建xml文档_Php_Xml_Dom - Fatal编程技术网

关于PHP5.x通过dom创建xml文档

关于PHP5.x通过dom创建xml文档,php,xml,dom,Php,Xml,Dom,我正在使用PHP的DOMDocument类创建一个xml文件,我的代码是: $xmlObject = new DOMDocument('1.0', 'utf-8'); //root node -- books $books = $xmlObject->createElement('books'); //book node $book = $xmlObject->createElement('book'); //book node's a

我正在使用PHP的
DOMDocument
类创建一个xml文件,我的代码是:

    $xmlObject = new DOMDocument('1.0', 'utf-8');
    //root node -- books
    $books = $xmlObject->createElement('books');
    //book node
    $book = $xmlObject->createElement('book');
    //book node's attribute -- index
    $index = new DOMAttr('index', '1');
    $book->appendChild($index);
    //name node
    $name = $xmlObject->createElement('name', 'Maozedong');
    //name node's attribute -- year
    $year = new DOMAttr('year', '1920');
    $name->appendChild($year);
    $book->appendChild($name);
    //story node
    $story = $xmlObject->createElement('story');
    $title = $xmlObject->createElement('title', 'Redrevolution');
    $quote = $xmlObject->createElement('quote', 'LeaveoffHunan');
    $story->appendChild($title);
    $story->appendChild($quote);
    $book->appendChild($story);
    $books->appendChild($book);
    if ($xmlObject->save('xml/books.xml') != false){
        echo 'success';
    }else{
        echo 'error';
    }
books.xml的内容只有一行:

<?xml version="1.0" encoding="utf-8"?>


另一个节点不存在。我的代码中有错误吗?

我忘记了将books节点附加到$xmlObject。 加:
$xmlObject->appendChild($books)

我喜欢用琴弦演奏。制作一个XML字符串,将其保存到文件中。您的代码将更短,运行更快,可读性更好
$xmlString=“1…etc”
但询问您的代码是否有任何错误就是要求进行否决票,甚至是结束投票。编辑您的原始答案,而不是更改答案