convert xml data into mysql insert/update query using php

断了今生、忘了曾经 提交于 2019-12-04 14:53:34

问题


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.



来源:https://stackoverflow.com/questions/25654204/convert-xml-data-into-mysql-insert-update-query-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!