convert xml data into mysql insert/update query us

2019-03-22 09:09发布

问题:

I am working on this project that basically reads the data from xml file and insert/update the data into mysql database.

Here is the sample.xml file:

<table name="movies">
    <column name="movie_name">Titanic</column>
    <column name="dvd">40</column>
    <column name="blueray">5</column>
    <column name="netflix">4</column>
    <column name="amazon">3</column>
</table>

I break down the problem into: 1) Get the values from XML file. 2) Insert the extracted values into mysql database.

I am able to work on insert the values to database, but the hard part is getting the values from xml making me crazy.

Here is my Database Table looks like:

Database name: Movies Columns: movie_name, dvd, blueray, netflix, amazon

Here is the code that I tried to extract the attribute values from xml.

<?php
$source = 'sample.xml';
// load as string
$xml = new SimpleXMLElement($source,null,true);
$movie_name= $xml->column->attributes()->name;
echo $movie_name. "\n";
?>

Output: Instead of getting the name of movie "Titanic", I get "movie_name".

回答1:

You can use this query:

<?php
$source = 'sample.xml';
// load as string
$xml = new SimpleXMLElement($source,null,true);
$movie_name= $xml->column->attributes()->name;

//echo $movie_name. "\n";

$table = $xml->attributes()->name;    

    $columns ="";
    foreach($xml as $column){
        $columns .= (string)$column->attributes()->name .",";
    }
    $columns = rtrim($columns, ",");

    $values ="";
    foreach($xml->column as $value){
        $values .= $value ."," ;
    }
    $values = rtrim($values, ",");

$query = " INSERTO INTO  $table ( $columns ) VALUES ( $values ) ";   

echo $query;

?>


回答2:

You're getting back exactly what you asked for. attributes() looks at the attributes, name gives you the name of the attribute. You can get the name by doing this

$movieName = (string)$xml->column;

If you want all the values, you can loop through the columns

foreach($xml->column as $xColumn) {
  $value = (string)$xColumn;
}


回答3:

the value of the name attribute IS movie_name. Titanic is the value of the Column element that has the name attribute with the value.