我正在尝试获取值或所有a:属性

时间:2019-05-12 12:29:31

标签: php xml simplexml xml-namespaces xmlnode

我使用过PHP SimpleXML,simplexml_load_string,即使使用DOM和SimpleXML之后也没有任何响应

// Php XML响应

$xml = <<<XML
    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
    <StatusResponse xmlns="http://tempuri.org/">
    <Result xmlns:a="http://schemas.datacontract.org/2004/07/OS.FLC" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:ResCode>OK</a:ResCode>
    <a:IDNumber>149897</a:IDNumber>
    <a:CusName>AXIOS ASOS</a:CusName>
    <a:HoldName>AXA AXIOS</a:HoldName>
    </Result>
    </StatusResponse>
    </s:Body>
    </s:Envelope>
    XML;

//使用PHP SIMPLE XML

$domContent = new SimpleXMLElement(((string)$xml), LIBXML_COMPACT);
$test = $domContent->xpath('/Result/a/*');
foreach ($test as $node) 
{
     print_r($node);
}

//使用DOM

$domp = new DOMDocument('1.0', 'utf-8');
$domp->loadXML($xml);
$items = $domp->getElementsByTagName('a');
foreach ($items as $item) 
{
     $HOLDER = $item->getElementsByTagNameNS("http://schemas.datacontract.org/2004/07/OS.FLC", "*")->Result(0)->nodeValue;
     echo "HoldName = " . $HOLDER . PHP_EOL;
}


// Expected Result

ResCode = OK
IDNumber = 149897
CusName = AXIOS ASOS

1 个答案:

答案 0 :(得分:0)

使用DOMDocument,您可以使用getElementsByTagNameNS并指定a的整个URL:

$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML($xml);

$elements = $doc->getElementsByTagNameNS('http://schemas.datacontract.org/2004/07/OS.FLC', '*');
foreach($elements as $elem)
{
    echo $elem->nodeName . ' -> ' . $elem->nodeValue ;
}

输出:

a:ResCode -> OK
a:IDNumber -> 149897
a:CusName -> AXIOS ASOS
a:HoldName -> AXA AXIOS