How can export mysql data in to xml using php
When we are dealing with XML and HTML, the best way to act is ever through a parser.In this particular situation, operating with a parser guarantees a valid XML and a clean, short code.
After defining mySQL query, we init a new DOMDocument
with version and encoding, then we set his ->formatOutput
to True to print out XML in indented format:
$query = "SELECT AB.id, AB.name, AB.firstname, AB.street, AB.zipcode, AB.city_id, CI.city FROM address_book AS AB INNER JOIN city AS CI ON AB.city_id = CI.id";$dom = new DOMDocument( '1.0', 'utf-8' );$dom ->formatOutput = True;
Then, we create the root node and we append it to DOMDocument
:
$root = $dom->createElement( 'addressbook' );$dom ->appendChild( $root );
At this point, after executing mySQL query, we perform a while
loop through each resulting row; for each row, we create an empty node <address>
, then we perform a foreach
loop through each row's field. For each field, we create an empty childnode with tag as field key, then we append to childnode the field value as CDATA and the same childnode to <address>
node; at the end of each while
loop, each <address>
node is appended to root node:
$result = $mysqli->query( $query );while( $row = $result->fetch_assoc() ){ $node = $dom->createElement( 'address' ); foreach( $row as $key => $val ) { $child = $dom->createElement( $key ); $child ->appendChild( $dom->createCDATASection( $val) ); $node ->appendChild( $child ); } $root->appendChild( $node );}
Now, your XML is ready.
If you want save it to a file, you can do it by:
$dom->save( '/Your/File/Path.xml' );
Otherwise, if you prefer send it as XML you have to use this code:
header( 'Content-type: text/xml' );echo $dom->saveXML();exit;
If you want instead output it in HTML page, you can write this code:
echo '<pre>';echo htmlentities( $dom->saveXML() );echo '</pre>';
- See more about DOMDocument