关于php 5.x由dom文档创建xml

时间:2012-10-25 16:40:38

标签: php xml dom

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

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

1 个答案:

答案 0 :(得分:-2)

我忘记将books节点附加到$ xmlObject。 加: $ xmlObject-&GT;使用appendChild($书籍);