感谢在此方面的一些帮助。我有一个很长的 xml 表单,其中有 80 多个项目要插入到我的数据库中。
我已经对此进行了研究,但出于某种原因,我的 foreach 循环不起作用。
我已经减少了此处的插入内容,以便了解我正在尝试做什么。
我可以将第一个“属性/项目”插入到数据库中,所以我知道插入等操作没有问题。
出于某种原因,循环不会显示数据库中的其他 79 个项目。
$affectedRow = 0;
$xml = simplexml_load_file('properties2.xml') or die("can not find it");
foreach($xml->children() as $row) {
$reference = $row->branch->properties->property['reference'];
$instructedDate = $row->branch->properties->property->instructedDate;
$price_text = $row->branch->properties->property->price_text;
$sql = "INSERT INTO test( reference, instructedDate, price_text) VALUES ('". $reference ."','". $instructedDate ."','". $price_text ."')";
$result = mysqli_query($conn, $sql);
if (! empty($result )) {
$affectedRow ++;
} else {
$error_message = mysqli_error($conn) . "\n";
}
}
?>
例如xml文件
-<agency branchName="billies Estate Agents " name="billie ea" xsi:noNamespaceSchemaLocation="http://www.feedcompany.co.uk/xmlexport/feedcompanyXMLSchema.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<branches>
-<branch name="billies Estate Agents ">
-<properties>
-<property reference="00000477">
<instructedDate>26/02/2018 15:11:56</instructedDate>
<price_text>Offers in Excess of £200,000</price_text>
</property
-<property reference="00000478">
<instructedDate>26/02/2018 15:11:56</instructedDate>
<price_text>Offers in Excess of £200,000</price_text>
</property>
最佳答案
因为 $xml->children()
,您只能将第一个元素放入数据库中不是你所期望的。
请注意,您的 XML 以 <agency>
开头在它之后你有<branches>
标签。我猜你的完整 XML 是这样的:
<agency>
<branches>
<branch>
<properties>
<property>
...
</property>
<property>
...
</property>
</properties>
</branch>
</branches>
</agency>
你想获得所有属性 -> 所以你需要使用 $xml->branches->branch->properties->children()
.
类似于:
foreach($xml->branches->branch->properties->children() as $property) {
$sql = "INSERT INTO test( reference, instructedDate, price_text) VALUES ('". $property['reference']."','". $property->instructedDate ."','". $property->price_text."')";
...
}
当你执行 $xml->children()
正如在第 3 行中,您将分支标记作为数组中的唯一元素 - 这就是为什么您只有一个元素插入到您的数据库中。
关于php - 'simplexml' php 到 mysql 数据库循环只返回第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51714838/