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

时间:2016-07-06 22:50:18

标签: javascript php xml dom foreach

在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>";

?>

1 个答案:

答案 0 :(得分:0)

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();