首页 > 解决方案 > 在 foreach 循环中取消设置特定节点

问题描述

我完全被困在这里。

我在 PHP 中有一个简单的 xml 结构

<InvoiceLines>
<InvoiceLine>
    <SalesInvoiceProductLine>
        <ProductIdentifier type="customer">4867895346</ProductIdentifier>
        <ProductName>a name</ProductName>
        <ProductUnitPrice type="net">75</ProductUnitPrice>
        <ProductVatPercentage vatcode="KOMY">24</ProductVatPercentage>
        <SalesInvoiceProductLineQuantity>1</SalesInvoiceProductLineQuantity>
        <Dimension>
            <DimensionName>Kustannuspaikka</DimensionName>
            <DimensionItem>110 Tukkukauppa kotimaa</DimensionItem>
        </Dimension>
    </SalesInvoiceProductLine>
</InvoiceLine>
<InvoiceLine>
    <SalesInvoiceProductLine>
        <ProductIdentifier type="customer">1345573456</ProductIdentifier>
        <ProductName>name</ProductName>
        <ProductUnitPrice type="net">31</ProductUnitPrice>
        <ProductVatPercentage vatcode="KOMY">24</ProductVatPercentage>
        <SalesInvoiceProductLineQuantity>1</SalesInvoiceProductLineQuantity>
        <Dimension>
            <DimensionName>Kustannuspaikka</DimensionName>
            <DimensionItem>150</DimensionItem>
        </Dimension>
    </SalesInvoiceProductLine>
</InvoiceLine>
<InvoiceLine>
    <SalesInvoiceProductLine>
        <ProductIdentifier type="customer">Shipping_cost</ProductIdentifier>
        <ProductName>Shipping</ProductName>
        <ProductUnitPrice type="net">0</ProductUnitPrice>
        <ProductVatPercentage vatcode="KOMY">24</ProductVatPercentage>
        <SalesInvoiceProductLineQuantity>1</SalesInvoiceProductLineQuantity>
        <SalesInvoiceProductLineDiscountPercentage>0</SalesInvoiceProductLineDiscountPercentage>
    </SalesInvoiceProductLine>
</InvoiceLine>

我需要删除带有运费的 InvoiceLine。我已经尝试了很多(只是计算整个事情,删除最后一个,使用 xPath 的不同方法等)

我现在的代码

//remove shipping lines, always 0 and not needed
foreach ($base->SalesInvoice->InvoiceLines->InvoiceLine as $key => $invoiceline) {
  if ($invoiceline->SalesInvoiceProductLine->ProductIdentifier == "Shipping_cost") {
echo "shipping cost FOUND \n";
echo "\n";
var_dump($key);
echo "\n";
    unset($base->SalesInvoice->InvoiceLines->InvoiceLine[$key]);
  }
}

我无法理解这一点。它找到运输成本,但无法使未设置的工作。$key 变量只包含一个字符串(11)“InvoiceLine”。我尝试了更多方法,但到目前为止我没有找到正确的元素。

如果需要任何信息,请告诉我!

标签: phpsimplexml

解决方案


由于您正在处理 xml,因此使用 xpath 可能会更好。类似于以下内容:

dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$targets = $xpath->query('//ProductIdentifier[text()="Shipping_cost"]');

foreach ($targets as $target) {
    $target->parentNode->removeChild($target);
}

echo $dom->saveXML();

那应该为您提供正确的输出。


推荐阅读