[英]PHP - Generate XML in loop using DOM library
我正在从数据库查询中检索一组联系记录,然后需要生成一个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的语法。
很简单:
$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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.