【发布时间】:2016-07-13 14:36:34
【问题描述】:
我有一个 PHP 脚本,它读取 XML 文件并将其转换为我的 XML 格式。原始 XML 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<root>
<products>
<product>
<id>1</id>
<stock>23</stock>
... 6 more nodes....
<pictures>
<pic1>linktopic1.jpg</pic1>
<pic2>linktopic2.jpg</pic2>
</pictures>
<tax_percent>...</tax_percent>
<price_dc>....</price_dc>
...... some more nodes....
<attributes>
<attribute name="Sample attribute" value="Sample value" />
<attribute name="Sample attribute 2" value="Sample value 2"/>
.... 10+ attributes for each product....
</attributes>
</product>
</products>
</root>
我正在使用 XMLwriter 读取 XML 并写入新的 XML。位于不同节点中的所有图片和属性必须在 1 个字符串中。我设法为图片做到了这一点,但它不适用于属性。
foreach($xml->children() as $products) {
foreach($products->children() as $product) {
$newXML->startElement("product");
$newXML->writeElement("ID", $product->id);
$newXML->writeElement("Stock", $product->stock);
$pic=""; // string resets for each product node
$atr=""; // Attribute string
foreach($product->pictures as $child) { // pictures
if ($child->pic1!="") { $pic=$pic.$child->pic1.","; } // If the picture subnode exists it appends the image to previous ones
if ($child->pic2!="") { $pic=$pic.$child->pic2.","; }
if ($child->pic3!="") { $pic=$pic.$child->pic3.","; }
}
foreach($product->attributes as $child) { //attributes
if ($child->attribute['name']=="Sample attribute") { $atr=$atr.$child->attribute['name'].':'.$child->attribute['value'].','; }
if ($child->attribute['name']=="Sample attribute 2") { $atr=$atr.$child->attribute['name'].':'.$child->attribute['value'].','; }
}
..... some more spaghetti code....
就像我说的,图片代码可以正常工作,但出于某种原因,属性代码只将产品的第一个属性写入字符串并跳过所有其他属性。
谁知道为什么 foreach 循环会跳过所有其他属性节点?在我看来,它似乎有某种问题,因为属性节点具有相同的节点名称,而图片具有动态名称,idk..
【问题讨论】:
-
做过任何基本的调试,比如在你的属性循环中做一些非条件输出?检查循环是否确实看到所有属性节点。如果是这种情况,那么你的 if() 是不正确的并且没有正确触发。
-
你想要的输出是什么? 读取 XML 并写入新的 XML...输入 XSLT(不需要一个
foreach)。