且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PHP 将 XML 数据插入 MySQL 表

更新时间:2023-12-01 13:24:34

你需要编辑你的 XML 文档,用这个标签封装文档:
... </客户>

You need to edit your XML document, encapsulate the document with this tag:
<Customers> ... </Customers>

所以你的代码的开始部分应该是这样的:

So the beginning portion of your code should look like:

<?xml version="1.0"?>
$sXmlString =<<< END
<Customers>
  <Customer>
    <id>1</id>
    <name>Oluwafemi</name>
    <address>Cresent Drive, TX</address>
  </Customer>
</Customers>
END;

OP 无法编辑提供的 XML,我假设它是结构化的,其中将添加新客户并添加额外的 id、姓名、地址实体.这是 OP 的更新代码:

OP is unable to edit the XML provided, I assume it is structured where new customers would be added in with additional id, name, address entities. Here is the updated code for OP:

<?php
$xmlData =<<< END
<?xml version="1.0"?>
<Customer>
  <id>1</id>
  <name>Oluwafemi</name>
  <address>Cresent Drive, TX</address>
  <id>2</id>
  <name>Rob</name>
  <address> 123 Longhorn </address>
</Customer>
END;

$xml = simplexml_load_string($xmlData) or die("ERROR: Cannot create SimpleXML object");
$connection = mysqli_connect("localhost", "root", "", "Customers") or die ("ERROR: Cannot connect");

/* Assumes that the number of IDs = number of customers */
$size = sizeOf($xml->id);
$i = 0; //index

/* Add each customer to the database, See how we reference it as    $xml->ENTITY[INDEX] */
while($i != $size) 
{
    //echo $xml->id[$i]; //Test
    $sql = "INSERT INTO customerdata (id, name, address ) VALUES ('$xml->id[$i]', '$xml->name[$i]', '$xml->address[$i]')";
    mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");

    $i++; //increment index
}

mysqli_close($connection);

我还添加了一个包含数据的额外客户 ID.您可以删除它,代码仍然可以正常工作.

I also added in an additional customer id with data. You can remove that and the code will still work fine.