Generating an XML file with data from a MySQL database using the inbuilt SimpleXMLElement class.
By using this class you can avoid formatting errors and issues than if you were to build from output into strings.
The simple PDO MySQL connection with a SELECT loop:
$db = new PDO("mysql:host=127.0.0.1;dbname=test; charset=utf8", 'root', '');
$select = $db->query("SELECT `type`, `name`, `value`, `enabled` FROM `xml_data`;");
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
//Loop each row
} Now with SimpleXMLElement() the XML can be built from within the loop:
$xml = new SimpleXMLElement('<objects/>');
$select = $db->query("SELECT `type`, `name`, `value`, `enabled` FROM `xml_data`;");
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
($row['type'] === 'category') ? $obj = $xml->addChild('category') : $obj = $xml->addChild('tag');
$obj->addAttribute('enabled', $row['enabled']);
$obj->addChild('name', $row['name']);
$obj->addChild('value', $row['value']);
}
$xml->asXML('the_xml_file_name.xml');
Header('Content-type: text/xml');
print($xml->asXML()); This doesn’t look like much but when you see the output, the addAttribute and addChild becomes more apparent.
This will output:
<?xml version="1.0"?>
<objects>
<category enabled="1">
<name>tools</name>
<value>all</value>
</category>
<category enabled="1">
<name>food</name>
<value>all</value>
</category>
<category enabled="1">
<name>books</name>
<value>all</value>
</category>
<category enabled="0">
<name>vehicle_parts</name>
<value/>
</category>
<tag enabled="1">
<name>container</name>
<value>all</value>
</tag>
<tag enabled="1">
<name>shelves</name>
<value>all</value>
</tag>
<tag enabled="0">
<name>locker</name>
<value>all</value>
</tag>
</objects>
To save this as an XML file us asXML() :
$xml->asXML('the_xml_file_name.xml'); This will save the XML data into the file the_xml_file_name.xml
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…