Import XML with attributes into mysql

前端 未结 3 1871
梦谈多话
梦谈多话 2020-12-17 06:56

I have a large (~30Mb) XML file like this:




        
相关标签:
3条回答
  • 2020-12-17 07:35
    $url = 'FILE.xml';
    $xml = simplexml_load_file($url);
    for($i=0;$i<count($xml->Item);$i++)
    {
       print_r($xml->Item[$i]);
     }
    
    0 讨论(0)
  • 2020-12-17 07:38

    First create a table that matches all possible fields as columns. Then you can load it by a LOAD XML LOCAL INFILE query.

    LOAD XML LOCAL INFILE 'file.xml'
      INTO TABLE person
      ROWS IDENTIFIED BY '<Item>';
    
    0 讨论(0)
  • 2020-12-17 07:53

    I try to answer my question.

    <?php
        $url = 'FILEXML';
        $xml = simplexml_load_file($url);    
    $i = 1;
      foreach($xml->xpath("/LIC/Item") as $docs)
      {
            foreach($docs->Field as $field) 
            {
                $resultstr[] = $field["Name"];
            }
        $sql_head = headquote($resultstr);
        $sql_ins = "INSERT INTO table_name (";
        $sql_dec = ") VALUE (";
        unset($resultstr);
        $fresult = (array)$docs;
        $fvalue = array_pop($fresult);
        $sql_val = numking($fvalue);
        $sql_end = ");";
        $query_to_use_for_mysql = ($sql_ins.$sql_head.$sql_dec.$sql_val.$sql_end);
    
        unset($fresult);
        unset($fvalue);
     }
     ?>
    

    And add this two functions:

    <?php
        function headquote($hdarray) {
                $hdata   = array();
                foreach ( $hdarray as $hdval ) {
                    #       Use backticks instead quotes!
                $hdata[] = "`$hdval`";
                  }
            $hdarray = implode($hdata, ',');
            return $hdarray;
         }
        function numking($input) {
                $data   = array();
                foreach ( $input as $value ) {
                $data[] = is_numeric($value) ? $value : "'".mysql_escape_string($value)."'";
                 }
                $input = implode($data, ',');
                return $input;
          }
    ?>
    

    Thanks to all for help!

    0 讨论(0)
提交回复
热议问题