020 555 1111
  • Old fashion, modular, procedural PHP plus some scaffolding techniques to allow it to mimic MVC simplicity.
  • A quick reference to help you find in PHP maze what needs to be done and how to do it.
  • Learn a PHP Object Oriented Programming by building a live discussion forum application.
  • MVC - Model View Controller - real life, easy reference and application.
This product has options, take a look at them and select ones you like the most.
Options are displayed under image section.
Top » XML

Create XML using PDO db fetch and SimpleXML
[SimpleXML example]

A nice idea to create XML using SimpleXML

//db connection - does not require try/catch, as it is handled by global exception handler
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$dbh->exec("SET CHARACTER SET utf8");
$sql = 'SELECT cn, iso_2, iso_3 FROM ct WHERE id < 5';
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->bindColumn('cn', $cn, PDO::PARAM_STR);
$sth->bindColumn('iso_2', $iso_2, PDO::PARAM_STR);
$sth->bindColumn('iso_3', $iso_3, PDO::PARAM_STR);
$result = $sth->fetch();

//inst. SimpleXML
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><countries></countries>');

while ($result = $sth->fetch()) {
    //create nod
    $nod1 = $xml->addChild('country');
    //add children to node
    //you may consider using: htmlspecialchars(utf8_encode($cn)) to "well form" xml
    $nod1->addChild('cs', $cn);
    $nod1->addChild('iso_2', $iso_2);
    $nod1->addChild('iso_3', $iso_3);
}

// write to file
file_put_contents('example.xml', $xml->asXML());

 

output:

<countries>
    <country>
        <name>Albania</name>
        <iso2>AL</iso2>
        <iso3>ALB</iso3>
    </country>
    <country>
        <name>Algeria</name>
        <iso2>DZ</iso2>
        <iso3>DZA</iso3>
    </country>
    <country>
        <name>American Samoa</name>
        <iso2>AS</iso2>
        <iso3>ASM</iso3>
    </country>
</countries>