PHP - 使用DOM库在循环中生成XML

时间:2015-11-03 06:55:48

标签: php xml

我正在从数据库查询中检索一组联系人记录,然后我需要生成一个返回给浏览器的XML响应。

检索记录的PHP循环如下所示:

foreach($contacts as $contact){

        $firstName = $record->getField('first') ;
        $lastName = $record->getField('last') ;


    $recnum++; }

我需要生成的XML如下所示:

<?xml version="1.0" encoding="utf-8"?>
 <contacts>
    <contact>
        <first_name>Penny</first_name>
        <last_name>Lancaster</last_name>
    </contact>
    <contact>
        <first_name>Geoff</first_name>
        <last_name>McDermott</last_name>
    </contact>
 </contacts>

在使用之前,我已经能够创建一个硬编码的XML响应:

 $doc = new DOMDocument('1.0', 'utf-8');
 $doc->formatOutput = true;

 $root = $doc->createElement('error');
 $doc->appendChild($root);

 $desc = $doc->createElement('description', $error);
 $root->appendChild($desc);

 echo $doc->saveXML();

但我无法弄清楚将其合并到循环中并动态生成XML的语法。

1 个答案:

答案 0 :(得分:0)

非常简单:

$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$contactsElement = $doc->createElement('contacts');

foreach($contacts as $contact){
    // your loop, is working? What is $record?
    $firstName = $record->getField('first') ;
    $lastName = $record->getField('last') ;
    $recnum++; // is useful for something?

    $contactElement = $doc->createElement('contact');
    $firstNameElement = $doc->createElement('first_name', $firstName);
    $lastNameElement = $doc->createElement('last_name', $lastName);

    $contactElement->appendChild($firstNameElement);
    $contactElement->appendChild($lastNameElement);
    $contactsElement->appendChild($contactElement);
}

echo $doc->saveXML();