1

I have used PHP SimpleXML, simplexml_load_string, and i get no response even after using DOM and SimpleXML

//Php XML Response

$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;

// using PHP SIMPLE XML

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

//Using 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
Zee4real
  • 17
  • 5
  • mine is different as the nodes contain columns OK 149897 AXIOS ASOS AXA AXIOS How can i get this values – Zee4real May 12 '19 at 14:24
  • Different ? Really ? I just see more namespaces than in the duplicated question above. The basics are the same => `var_dump($domContent->children('s', true)->Body->children()->StatusResponse->Result->children('a', true))`. We can agree this is ugly. But if you want to use XPath with simplexml, you have to [register every namespace your are using](https://www.php.net/manual/en/simplexmlelement.xpath.php#115957) – Zeitounator May 12 '19 at 14:46

1 Answers1

0

Using DOMDocument, you can use getElementsByTagNameNS and specify the whole URL of a :

$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 ;
}

Output :

a:ResCode -> OK
a:IDNumber -> 149897
a:CusName -> AXIOS ASOS
a:HoldName -> AXA AXIOS
Joffrey Schmitz
  • 2,393
  • 3
  • 19
  • 28
  • thanks this works, But how do i target a specific node let's say for example $elem->CusName. Or I just want the get the value of a:IDNumber how do i go about this - Newbie here – Zee4real May 12 '19 at 14:57
  • You can replace the `*` (which mean 'all') in the second argument of the function per the element you want to target (e.g. `CusName`) – Joffrey Schmitz May 12 '19 at 15:20