PHP SimpleXML Step By Step Tutorial - Part 2: At previous post, we have learned how to create simple xml document use SimpleXML. In this post, we try to apply creating XML document from database. I use mysql database.
First, prepare a database named "test". You can use phpMyAdmin (a database management web based) for simply job.
Then, create a table named "books". You can execute this query:
CREATE TABLE `books` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(150) NOT NULL,
`author` varchar(150) NOT NULL,
`description` varchar(255) NOT NULL,
`on_sale` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
);
Next, insert several sample data:
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (1, 'PHP AJAX', 'Andreas', 'This is good book for learning AJAX', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (2, 'PHP Eclipse ', 'George', 'Nice book', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (3, 'PHP Prado', 'Junyian', '-', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (4, 'PHP Zend Framework', 'Ozulian', 'great', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (5, 'PHP Web Services', 'Bobi', '', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (6, 'PHP API', 'Hugo', '', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (7, 'PHP SEO', 'Monteo', '', 1);
Our database is ready. Now, we write code for generate xml document using SimpleXML:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "admin";
$dbname = "test";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$sql = "SELECT * FROM books";
$q = mysql_query($sql) or die(mysql_error());
$xml = "<library>";
while($r = mysql_fetch_array($q)){
$xml .= "<book>";
$xml .= "<id>".$r['id']."</id>";
$xml .= "<title>".$r['title']."</title>";
$xml .= "<author>".$r['author']."</author>";
$xml .= "<description>".$r['description']."</description>";
$xml .= "<on_sale>".$r['on_sale']."</on_sale>";
$xml .= "</book>";
}
$xml .= "</library>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test.xml");
?>