0

我正在使用DOMDocumentPHP 类来创建一个 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"?>

另一个节点不存在。我的代码中是否有任何错误?

4

1 回答 1

-2

我忘记将书籍节点附加到 $xmlObject。添加:$xmlObject->appendChild($books);

于 2012-10-25T16:44:17.917 回答