【发布时间】:2019-01-13 20:08:02
【问题描述】:
感谢您对此提供的帮助。我有一个很长的 xml 表单,其中包含 80 多个要插入到我的数据库中的项目。
我对此进行了研究,但由于某种原因,我的 foreach 循环不起作用。
我已经减少了此处的插入内容,以便了解我想要做什么。
我可以将第一个 'property / item 插入到数据库中,所以我知道插入等没有问题。
由于某种原因,循环不会显示数据库中的其他 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 文件的简短示例,以便其他人可以测试(不需要或想要所有 80 个项目)?
-
始终在开发和测试代码时,在 PHP 中启用错误显示。如果未找到 XML 引用(因为
children()未完全返回您所期望的),您可能在循环中遇到致命错误。在脚本的顶部error_reporting(E_ALL); ini_set('display_errors', 1); -
请注意,这容易受到二次 SQL 注入的影响。使用 mysqli,您应该使用
prepare()/bind_param(),execute()。有关示例,请参阅How can I prevent SQL injection in php。 -
戴夫,我如何显示这些值?你的意思是呼应他们?迈克尔,当我粘贴时没有任何反应.. 我使用 error_message 显示出现问题时,即没有变量匹配或拼写错误等
-
是的,我可以在页面上回显我想要的每个元素...但仅适用于第一个属性...没有循环
标签: php mysql xml loops foreach