php - 在 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”。我尝试了更多方法,但到目前为止我没有找到正确的元素。
如果需要任何信息,请告诉我!
解决方案
由于您正在处理 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();
那应该为您提供正确的输出。
推荐阅读
- azure - Azure 上的 Umbraco:找不到模板和 System.Net.Sockets.SocketException
- bash - 使用 sudo 别名启动 Midnight Commander `mc` 并保留路径
- android - 片段未出现在托管活动中
- c# - 在 Xamarin iOS 中打开 url 后是否应该处理 NsUrl?
- mapbox - 使用 Mapbox SDK 6.7 启用 pro Guard 时无法生成构建
- c++ - 静态声明时的c ++复制构造错误
- javascript - 如何使用 socket.io 接收数据?
- .net - Microsoft Bot Framework OAuth 卡返回错误请求
- javascript - 如何创建 Konva-React 上下文菜单
- c++ - GNU 链接器:适应名称修改算法的更改