Moses Byanyuma Moses Byanyuma - 1 year ago 62
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

#Programmer: Moses Byanyuma


// 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');

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


Answer Source

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(

// 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

// create and apppend and attribute
$attribute = $foo->appendChild(
// the value is actually a text node

echo $document->saveXml();