代码之家  ›  专栏  ›  技术社区  ›  MBF

PHP导入/解析XML文件内容保存到数据库

  •  0
  • MBF  · 技术社区  · 3 年前

    正在尝试将sms日志导入php,以便在mysql数据库中进行解析。 无法分析单个数组值,无法获取所有记录的完整数组。

    文件加载,能够成功打印整个输入数组,但foreach循环只返回一个结果,而不是全部13个,并且为空。

    // Load xml file else check connection
    $xml = simplexml_load_file("input.xml") or die("Error: Cannot load file");
    $con = json_encode($xml);
    $newXML = json_decode($con, true);
    
    print_r($newXML['sms']); //Output: Prints 0-4 lines successfully all together in array
    
    foreach ($newXML['sms'] as $attrib) {
        
        $date = $attrib->date;
        $body = $attrib->body;
        echo $date . " - " . $body; // test output (fails and returns empty)
    
    //Save Each Separate array line (sms message record) info to Db...
    ...
    

    XML文件布局:

    <?xml version="1.0" encoding="UTF-8"?>
    <smsgroup>
        <sms address="1234567" time="Apr 30, 2022 1:00:00 PM" date="1555987654339" type="2" body="message 5" read="1" />
        <sms address="1234567" time="Apr 30, 2022 1:00:00 PM" date="1555987654333" type="1" body="sms 4" read="1" />
        <sms address="5555555" time="Apr 30, 2022 1:00:00 PM" date="1555987654329" type="1" body="another message 3" read="1" />
        <sms address="5555555" time="Apr 30, 2022 1:00:00 PM" date="1555987654324" type="1" body="message 2" read="1" />
        <sms address="1234567" time="Apr 30, 2022 1:00:00 PM" date="1555987654321" type="2" body="message 1" read="1" />
    </smsgroup>
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Ahmet Feyzi    3 年前

    试试这个:

    foreach ($newXML['sms'] as $attrib) {
        $date = $attrib["@attributes"]["date"];
        $body = $attrib["@attributes"]["body"];
        echo $date . " - " . $body; 
    }
    
        2
  •  0
  •   Parfait    3 年前

    考虑使用 LOAD XML .Below可以作为PHP中的任何其他SQL命令运行。

    假设所有属性名称都与表名称匹配(尽管不匹配的名称将被忽略):

    LOAD XML LOCAL INFILE 'input.xml' 
      INTO TABLE myTable 
      ROWS IDENTIFIED BY '<sms>';
    

    或者,将局部变量与 SET 对于特定列或不同名称的表名:

    LOAD XML LOCAL INFILE 'input.xml'
      INTO TABLE myTable (@date, @body) 
      ROWS IDENTIFIED BY '<sms>'
      SET date_column=@date, body_column=@body; 
    
        3
  •  0
  •   Nigel Ren    3 年前

    您可以通过正确使用SimpleXML简化代码,而不必对数据进行json编码和解码。。。

    使用 -> 访问元素和 [] 访问属性。

    $xml = simplexml_load_file('input.xml') or die('Error: Cannot load file');
    
    foreach ($xml->sms as $attrib) {
        $date = $attrib['date'];
        $body = $attrib['body'];
        echo $date . ' - ' . $body; // test output (fails and returns empty)
    }