php - 使用 XMLWriter 生成 XML 文件

php - generating an XML file with XMLWriter

我正在尝试通过以下循环创建一个包含人名及其 children 的 XML 文件:

$xml_file = new XMLWriter();

$xml_file->startElement("People");

while ($list_of_people->current != NULL ){

    $xml_file->writeElement("Person"); // create a new person

    $xml_file->startElement('Person'); 

    $xml_file->writeAttribute('name', $list_of_people->current->name); // add their name as an attribute 

    if ($list_of_people->current->children != NULL){ 

        while ($list_of_people->current->child_current != NULL){ // if they have children create them as well 

            $xml_file->writeElement("Person");

            $list_of_people->startElement('Person'); 

            $xml_file->writeAttribute('name', $list_of_people->current->child_current->child_name);

            $xml_file->endElement(); 

            $list_of_people->current->child_current = $list_of_people->current->child_current->next;
        }
    } 

    $xml_file->endElement(); 

    $list_of_people->current = $list_of_people->current->next;
}

如您所见,在输出文件中,我应该有多个名为 "Person" 的元素,具体取决于列表中有多少人以及其中有多少人 children。

我希望最终 XML 文档看起来像这样的示例:

<People>
 <Person name="Anna"></Person>
 <Person name="Joe">
   <Person name="Willy"></Person> // Joe has a child named Willy
 </Person>
<Person name="Rob"></Person>
</People>

现在,我担心的是,我怎么知道 $xml_file->startElement('Person');选择了我刚刚创建的当前人,而不是之前已经创建的任何 Person 元素,因为它们的名称都相同?

以及如何访问最终 XML 文件的各个元素(如果它们同名)?

最后,我想保存此 XML 文档并将其内容打印到标准输出。

谢谢!

startElement 方法不是 select 当前的人,而是启动另一个人。事实上,您可以使用 writeElement 或 startElement 添加元素,但不能同时使用两者。

看这个例子:

<?php
    $people = array(
        array('name' => 'Anne', 'children' => array()),
        array('name' => 'Joe', 'children' => array(array('name' => 'Willy')))
    );

    //create a new xmlwriter object
    $xml = new XMLWriter(); 

    // Used to write to xml file - uncomment the next line to print xml to a file
    // $xml->openURI('people_test.xml');

    // used for string output from memory
    $xml->openMemory(); // comment this line to print xml to a file

    //set the indentation to true
    $xml->setIndent(true);

    //create the document tag
    $xml->startDocument();

    $xml->startElement("People"); // start People

    foreach($people as $person) {

        $xml->startElement("Person"); // start Person
        $xml->writeAttribute('name', $person['name']);

        if(!empty($person['children'])) {
            foreach($person['children'] as $child) {
                $xml->startElement("Person"); // start Person
                $xml->writeAttribute('name', $child['name']);
                $xml->endElement();
            }
        }
        $xml->endElement(); //End Personn

    }

    $xml->endElement(); //End People

    // Display thue current buffer
    echo $xml->flush(); 


?>