使用 PHP 将 XML 数据插入 MySQL 表 [英] Insert XML Data to MySQL Table Using PHP
问题描述
我正在尝试将 xml 数据插入到我的 sql 中,但它没有插入.如何为这种类型的xml编写foreach(xml->).xml是在这种结构中动态生成的.这是这种格式的示例xml
I am trying to insert xml data to my sql but it is not inserting. how to write the foreach(xml->) for this type of xml.the xml is generated dynamically in this structure.this is a sample xml in this format
<?php
$xmlData =<<< END
<?xml version="1.0"?>
<Customer>
<id>1</id>
<name>Oluwafemi</name>
<address>Cresent Drive, TX</address>
<list>
<contact>56689</contact>
<telephone>5889745</telephone>
</list>
<offer>congrats</offer>
</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");
foreach ($xml->Customer as $Customer) {
$id = $Customer->id;
echo "$id";
$name = $Customer->name;
$address = $Customer->address;
$sql = "INSERT INTO customerdata (id, name, address ) VALUES ('$id', '$name', '$address')";
mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");
}
mysqli_close($connection);
?>
推荐答案
你需要编辑你的 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.
这篇关于使用 PHP 将 XML 数据插入 MySQL 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!