如何使用 Foreach 循环使用 ext/dom 输出 XML



在 php 脚本上,如何使用字符串和/或 ext/dom 执行 foreach 循环来输出从 msql 数据库获取值的 XML 数据?已编辑:最新作品

<?php
#Programmer: Moses Byanyuma
require('./.env');

// Opens a connection to a mySQL server
try {
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME. ';charset=utf8',  DB_USERNAME, DB_PASSWORD);
} catch (PDOException $e) {
    echo "An Error occured, could not connect!";
}
$statement = $db->query('SELECT * FROM markers');
$xml = new DOMDocument("1.0");
$xml->formatOutput = true;
$markers = $xml->createElement('markers');
$markers = $xml->appendChild($markers);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
     $marker = $xml->createElement('marker');
     $markers->appendChild($marker);
     $marker->setAttribute('name', $row['name']);
    $marker->setAttribute('lat', $row['lat']);
    $marker->setAttribute('lng', $row['lng']);
    $marker->setAttribute('address', $row['address']);
    $marker->setAttribute('type', $row['type']);
}

echo "<xmp>".$xml->saveXML()."</xmp>";
?>

DOMDocument::createAttribute()没有第二个参数。我建议使用DOMElement::setAttribute().但是,如果您愿意,可以将属性创建为节点:

$document = new DOMDocument();
$foo = $document->appendChild(
  $document->createElement('foo')
);
// just set the attribute
$foo ->setAttribute('one', '1');
// create and configure the attribute node
$attribute = $document->createAttribute('two');
$attribute->value = '2';
// set it on the element
$foo->setAttributeNode($attribute);
// create and apppend and attribute
$attribute = $foo->appendChild(
  $document->createAttribute('three')
);
// the value is actually a text node
$attribute->appendChild(
  $document->createTextNode('3')
);
echo $document->saveXml();

最新更新