Translate

Tuesday 7 October 2014

Convert XML to ARRAY with Database using PHP


Explaination:
        In  this POST i expained convert XML to array for one simple XLM file.
        BY using this we can easily insert the datas into database.For that we have to do 
        connect to the database and include array.php file and xmlparser.php.This two files
        is use for to convert xml to array.
        This can be used for API Projects.

The database fields are:
    The fields we have to create in DB:
    1.id
    2.field1
    3.field2
    4.field3    

Array.php:

<?
Class XML2Ary {
public static function CreateArray ($XmlFilePath) {
if (!file_exists($XmlFilePath)) return FALSE;
$Class = Array();
$Class['UsersFileXml'] = file_get_contents($XmlFilePath);
$Class['FileXml'] = simplexml_load_string($Class['UsersFileXml']);
$Class['FileJson'] = json_encode($Class['FileXml']);
$Array = json_decode($Class['FileJson'],TRUE);
unset($Class);

return $Array;
}   
}?>


xmlparser.php:


<?php
/* xml parsing and conversion methods below start*/
 function xml2ary(&$string) {
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($parser, $string, $vals, $index);
    xml_parser_free($parser);

    $mnary=array();
    $ary=&$mnary;
    foreach ($vals as $r) {
        $t=$r['tag'];
        if ($r['type']=='open') {
            if (isset($ary[$t])) {
                if (isset($ary[$t][0])) 
    $ary[$t][]=array(); 
    else
     $ary[$t]=array($ary[$t], array());
                $cv=&$ary[$t][count($ary[$t])-1];
            } 
   else $cv=&$ary[$t];
            if (isset($r['attributes']))
   {
   foreach ($r['attributes'] as $k=>$v) 
   $cv['_a'][$k]=$v;
   }
            $cv=array();
            $cv['_p']=&$ary;
            $ary=&$cv;

        } 
  elseif
  ($r['type']=='complete')
   {
            if (isset($ary[$t])) { // same as open
                if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                $cv=&$ary[$t][count($ary[$t])-1];
            } else $cv=&$ary[$t];
            if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
            $cv['_v']=(isset($r['value']) ? $r['value'] : '');

        } elseif ($r['type']=='close') {
            $ary=&$ary['_p'];
        }
    }    
    
    _del_p($mnary);
  
 /*$path = $_SERVER['DOCUMENT_ROOT']."/complete_logs2";
 
 $path1 = $_SERVER['DOCUMENT_ROOT']."/complete_logs2/".$_SERVER['REMOTE_ADDR'];
 if (!file_exists($path1)) {
  mkdir($path1, 0777, true);
 }
 $path2 = $_SERVER['DOCUMENT_ROOT']."/complete_logs2/".$_SERVER['REMOTE_ADDR']."/".date("Y-m-d");
 if(!file_exists($path2)) {
  mkdir($path2, 0777, true);
 }
 $path3 = $_SERVER['DOCUMENT_ROOT']."/complete_logs2/".$_SERVER['REMOTE_ADDR']."/".date("Y-m-d")."/".date("H");
 if(!file_exists($path3)) {
  mkdir($path3, 0777, true);
 }
 $filename = strtotime("now")."_".mt_rand().".txt";
 $my_file = $path3."/".$filename;  
 $handle = @fopen($my_file, 'w');
 @fwrite($handle, var_export(array("Request"=>$string,"Response"=>$mnary),true));
 @fclose($handle);
 */
   
    return $mnary;
}

// _Internal: Remove recursion in result array
function _del_p(&$ary) {
    foreach ($ary as $k=>$v) {
        if ($k==='_p') unset($ary[$k]);
        elseif (is_array($ary[$k])) _del_p($ary[$k]);
    }
}

// Array to XML
function ary2xml($cary, $d=0, $forcetag='') {
    $res=array();
    foreach ($cary as $tag=>$r) {
        if (isset($r[0])) {
            $res[]=ary2xml($r, $d, $tag);
        } else {
            if ($forcetag) $tag=$forcetag;
            $sp=str_repeat("\t", $d);
            $res[]="$sp<$tag";
            if (isset($r['_a'])) {foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";}
            $res[]=">".((isset($r['_c'])) ? "\n" : '');
            if (isset($r['_c'])) $res[]=ary2xml($r['_c'], $d+1);
            elseif (isset($r['_v'])) $res[]=$r['_v'];
            $res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
        }
        
    }
    return implode('', $res);
}

// Insert element into array
function ins2ary(&$ary, $element, $pos) {
$ar1=array_slice($ary, 0, $pos); $ar1[]=$element;
$ary=array_merge($ar1, array_slice($ary, $pos));
}
/* xml parsing and conversion methods above  end*/

?>

<?php
$conn=mysql_connect("localhost","root","");
mysql_select_db("xmlarray",$conn);
?>

Database Connection:


<?php
$conn=mysql_connect("localhost","root","");
mysql_select_db("xmlarray",$conn);
?>

index.php:


<?php
include('array.php');
include('xmlparser.php');
$conn=mysql_connect("localhost","root","");
mysql_select_db("xmlarray",$conn);
$xml='<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
</note>';

$string=$xml;

$assd=htmlentities($xml);

$val=xml2ary($xml);
echo "<pre>";
print_r($val);
echo "</pre>";

$name=$val['note']['to']['_v'];
$from=$val['note']['from']['_v'];
$heading=$val['note']['heading']['_v'];
$result = mysql_query("INSERT INTO phparray (field1,field2,field3) VALUES ('$name','$from','$heading')");
 if($result==1)
 {
     echo 'inserted';
     }
 else
 {
     echo 'not inserted';
 }
?>


The inserted datas in Databse we have to fetch and display it in index page for
ur reference.


   Notes:
           phparray-->tablename

<table border="1" cellpadding="10" cellspacing="0">
    <tr>
    <td>S.no</td>
    <td>Field1</td>
    <td>Field2</td>
    <td>Field3</td>
    </tr>
    <?php
    $i=1;
$select=mysql_query("select * from phparray");
while($row=mysql_fetch_array($select))
{   
    ?>
    <tr>
    <td><?php echo $row['id'];?></td>
    <td><?php echo $row['key_field'];?></td>
        <td><?php echo $row['field2'];?></td>
            <td><?php echo $row['field3'];?></td>
            </tr>
<?php }?>
</table>

No comments:

Post a Comment