Moses Byanyuma Moses Byanyuma - 4 months ago 17
Javascript Question

How to use Foreach loop using the ext/dom to output XML

On a php script, how does one do a foreach loop using a string and/or the ext/dom to output XML data that gets values from a msql database?
EDITED: Latest work

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

?>

ThW ThW
Answer

DOMDocument::createAttribute() has no second argument. I suggest using DOMElement::setAttribute(). But you can create the attribute as a node if you like:

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