inwebdeveloper

Open Source Web Developers Resources

Parsing XML With PHP

Maybe it’s a lot of tutorials that teach how to parsing XML with PHP. However, only the basics. What if a little more complicated.

This time I made a tutorial how to parsing XML with PHP, then process the data into MySQL.


First, an XML file.

[php]
<db_admin>
<row>
<id_admin>1</id_admin>
<adm_nama>NAWA</adm_nama>
<adm_userid>nawa</adm_userid>
<adm_password>menur15b</adm_password>
</row>
<row>
<id_admin>2</id_admin>
<adm_nama>Admin</adm_nama>
<adm_userid>admin</adm_userid>
<adm_password>12345</adm_password>
</row>
</db_admin>
[/php]

Now, code in PHP.
[php]
<?php
require (‘config.php’);

$file = "mla_export_db_pengumuman.xml";

$table = explode(".",$file);
$table = explode("mla_export_",$table[0]);
$table = $table[1];

$xml = simplexml_load_file($file);
foreach($xml->row as $item){
$val = null;
foreach($item->children() as $child){
$val[] = "’".$child."’";
}
$values = join($val, ", ");

$sql = "INSERT IGNORE INTO $table VALUES ($values)";
//echo $sql."<br >";
if (!mysql_query($sql)) die(‘Error: ‘ . mysql_error());
}
?>
[/php]

How, easy right. But I make this script for 2 days.

Leave a Reply