I'm trying to figure out a way to populate an XML object more dynamically without having to constantly change the name of the nodes. I some code similar to this:
EDIT: Changed the data to be inline with actual db structure:
$query = ("Select order_id, created_on, updated_on, status from table orders;");
// Execute query
$result = mysql_query($query, $link) or die("Could not complete database query");
// Populate array
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
$doc = new DOMDocument();
$doc->formatOutput = true;
$r = $doc->createElement( "data" );
$doc->appendChild( $r );
foreach( $resultArray as $record )
{
$b = $doc->createElement( "record" );
$record1 = $doc->createElement( "Order" );
$record1->appendChild(
$doc->createTextNode( $record['order_id'] )
);
$b->appendChild( $record1 );
$record2 = $doc->createElement( "Created" );
$record2->appendChild(
$doc->createTextNode( $record['created_on'] )
);
$b->appendChild( $record2 );
$record3 = $doc->createElement( "Updated" );
$record3->appendChild(
$doc->createTextNode( $record['updated_on'] )
);
$b->appendChild( $record3 );
$record4 = $doc->createElement( "Status" );
$record4->appendChild(
$doc->createTextNode( $record['status'] )
);
$b->appendChild( $record4 );
$r->appendChild( $b );
}
echo $doc->saveXML();
// Close connection
mysql_close($link);
This is fine, but if I want to add a 3rd column in the query I have to also add it to the loop. I'm sure there is a better way to actually do this.
Any advice?
Thanks.