2 回答

TA貢獻1796條經驗 獲得超10個贊
問題是該元素GetVehiculesLocationResponse定義了一個新的默認命名空間,因此子元素都在該新命名空間中......
<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']");

TA貢獻1786條經驗 獲得超13個贊
考慮XSLT(XPath 的同級語言),它是一種專用語言,旨在轉換 XML 文件,特別適合處理許多元素。事實上,您甚至可以將參數001
從 PHP 傳遞到 XSLT。PHP 可以使用庫的xsl類運行 XSLT 1.0 腳本DOMDocument
。
XSLT
<?xml version="1.0" ?>?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? xmlns:googl="http://google.fr/">??
? ?<xsl:output method="xml" indent="yes"/>
? ?<xsl:strip-space elements="*"/>
? ?<!-- DEFINE PARAM WITH DEFAULT -->
? ?<xsl:param name="id_param">001</xsl:param>
? ? <!-- IDENTITY TRANSFORM -->
? ? <xsl:template match="@* | node()">
? ? ? ? <xsl:copy>
? ? ? ? ? ? <xsl:apply-templates select="@* | node()"/>
? ? ? ? </xsl:copy>
? ? </xsl:template>
? ? <!-- KEEP NODES BY PARAM VALUE -->
? ? <xsl:template match="googl:GetVehiculesLocationResult">
? ? ? ? <xsl:copy>
? ? ? ? ? ? <xsl:copy-of select="googl:Location[googl:idVH != $id_param]"/>
? ? ? ? </xsl:copy>
? ? </xsl:template>
</xsl:stylesheet>
PHP (在循環中將參數傳遞給 XSLT)
// LOAD XML
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->load($data->xmlFile);
// LOAD XSLT?
$xsl = new DOMDocument('1.0', 'UTF-8');? ?
$xsl->load('XSLT_Script.xsl');
// INITIALIZE TRANSFORMER
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
foreach($param as array('001', '002')) {?
? ? // SET PARAMETER VALUE
? ? $proc->setParameter('', 'id_param', $param);
? ? // TRANSFORM SOURCE
? ? $xml = $proc->transformToDoc($xml);
}
// ECHO TO SCREEN
echo $xml->saveXML();
// SAVE TO FILE
file_put_contents($data->xmlFile, $xml);
輸出
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
? ?<soap:Body>
? ? ? <GetVehiculesLocationResponse xmlns="http://google.fr/">
? ? ? ? ?<GetVehiculesLocationResult>
? ? ? ? ? ? <Location>
? ? ? ? ? ? ? ?<idVH>11111111</idVH>
? ? ? ? ? ? ? ?<date>2020-03-24T21:49:46</date>
? ? ? ? ? ? ? ?<latitude>1111111</latitude>
? ? ? ? ? ? ? ?<longitude>11111111</longitude>
? ? ? ? ? ? </Location>
? ? ? ? ?</GetVehiculesLocationResult>
? ? ? </GetVehiculesLocationResponse>
? ?</soap:Body>
</soap:Envelope>
- 2 回答
- 0 關注
- 200 瀏覽
添加回答
舉報