我需要使用PHP删除XML文件的元素。
这是我的XML文件
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetVehiculesLocationResponse xmlns="http://google.fr/">
<GetVehiculesLocationResult>
<Location>
<idVH>001</idVH>
<date>2020-06-30T09:06:39</date>
<latitude>111111</latitude>
<longitude>11111</longitude>
</Location>
<Location>
<idVH>002</idVH>
<date>2020-04-02T13:45:51</date>
<latitude>1111111</latitude>
<longitude>111111</longitude>
</Location>
<Location>
<idVH>11111111</idVH>
<date>2020-03-24T21:49:46</date>
<latitude>1111111</latitude>
<longitude>11111111</longitude>
</Location>
</GetVehiculesLocationResult>
</GetVehiculesLocationResponse>
</soap:Body>
</soap:Envelope>
我想删除idVH等于002的元素
我使用这个代码不工作
$xml1 = simplexml_load_string($result);
$items = $xml1->xpath("/soap:Envelope/soap:Body/GetVehiculesLocationResponse/GetVehiculesLocationResult/Location[idVH = 002]");
foreach ($items as $i) unset($i[0]);
echo $xml1->asXML();
问题是元素GetVeHiculeSocationResponse
定义了一个新的默认命名空间,因此和子元素都在该新命名空间中。。。
<GetVehiculesLocationResponse xmlns="http://google.fr/">
所以首先注册新的命名空间,然后在较低级别的元素中使用它作为前缀。。。
$xml1->registerXPathNamespace("d", "http://google.fr/");
$items = $xml1->xpath("/soap:Envelope/soap:Body/d:GetVehiculesLocationResponse/d:GetVehiculesLocationResult/d:Location[d:idVH = '002']");