dou12754 2015-03-28 14:47
浏览 59

如何将XML中的数据插入数据库[重复]

This question already has an answer here:

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 ?

</div>
  • 写回答

1条回答 默认 最新

  • dongtang1910 2015-03-28 16:35
    关注

    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);";
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法