-3

I want to insert the following XML file into a Mysql database using php

<?xml version="1.0" encoding="UTF-8"?>
<PrintLetterBarcodeData 
    uid="725733706873" 
    name="RAVINDER KUMAR" 
    gender="M" 
    yob="1996" 
    co="S/O KAKA RAM" 
    house="460A" 
    street="WARD NO. 6" 
    lm="NA" 
    loc="NA" 
    vtc="Nanyola (292)" 
    po="Naneola" 
    dist="Ambala" 
    state="Haryana" 
    pc="134003"
/>

How do I extract the data from this XML file to insert them into a database ?

dvhh
  • 4,724
  • 27
  • 33

1 Answers1

-1

For the PHP approach, you will find the following useful:

<?php
$string = <<<XML
  <PrintLetterBarcodeData 
    uid="725733706873" 
    name="RAVINDER KUMAR" 
    gender="M" 
    yob="1996" 
    co="S/O KAKA RAM" 
    house="460A" 
    street="WARD NO. 6" 
    lm="NA" 
    loc="NA" 
    vtc="Nanyola (292)" 
    po="Naneola" 
    dist="Ambala" 
    state="Haryana" 
    pc="134003"
  />
XML;


$xml = simplexml_load_string($string);
$attribs = $xml->attributes();
// convert the '$attribs' to an array
foreach($attribs as $key=>$val) {
    $arrayOfAttribs[(string)$key] = "'".(string)$val."'";
}
$namesOfColumns = implode(",", array_keys($arrayOfAttribs));
$valuesOfColumns = implode(",", array_values($arrayOfAttribs));

// your database stuff
$query = "INSERT INTO yourtable ($namesOfColumns) VALUES ($valuesOfColumns);";
?>
someOne
  • 1,975
  • 2
  • 14
  • 20
  • Recommended reading: [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/q/60174/367456) – hakre Mar 29 '15 at 07:18
  • @hakre Indeed that's a considerably interesting topic, but what I've provided is just a bare "How to" not considering any essential factor like security nor performance. – someOne Mar 29 '15 at 08:05
  • I perhaps should lower this a bit. The scenario here for the PHP part requires mysql fieldname validation. It's not well covered on this site. The other issue is about not using parametrized queries which would make the example much better IMHO. You're right that there is no requirement for you to provide that in an answer. It's just a comment of me. – hakre Mar 29 '15 at 08:13