Thomas L Durbin
Thomas L Durbin

Reputation: 63

Issues with API's XML PHP parsing

I am using an API however the way that they setup their returned XML is incorrect so I am needing to come up with a solution for parsing it. i am unable to convert to JSON (my preferred return method) because they don't support it. Below I have listed my XML and PHP.

XML Returned by API

<?xml version="1.0" encoding="utf-8"?>
<interface-response>
    <Domain>example.com</Domain>
    <Code>211</Code>
    <Domain>example.net</Domain>
    <Code>210</Code>
    <Domain>example.org</Domain>
    <Code>211</Code>
</interface-response>

Each Code is for the previous domain. I have no idea how to tie these two together and still be able to loop through all of the results returned. There will essentially be one Domain and one Code returned for each Top Level Domain, so a lot of results.

PHP code so far:

<?php
$xml = new SimpleXMLElement($data);
$html .= '<table>';
foreach($xml->children() as $children){
    $html .= '<tr>';
    $html .= '<td>'.$xml->Domain.'</td>';
    if($xml->Code == 211){
        $html .= '<td>This domain is not avaliable.</td>';
    }elseif($xml->Code == 210){
        $html .= '<td>This domain is avaliable.</td>';
    }else{
        $html .= '<td>I have no idea.</td>';
    }               
    $html .= '<tr>';
}
$html .= '</table>';
echo $html;
?>

Upvotes: 0

Views: 297

Answers (1)

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

If you don't want to deal with crappy XML (I'm not saying XML is crappy in general, but this one is) you could consider something like this:

<?php

$responses = [];
$responses['210'] = 'This domain is avaliable.';
$responses['211'] = 'This domain is not avaliable.';

$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<interface-response>
    <Domain>example.com</Domain>
    <Code>211</Code>
    <Domain>example.net</Domain>
    <Code>210</Code>
    <Domain>example.org</Domain>
    <Code>211</Code>
</interface-response>
XML;

$data = (array) simplexml_load_string($xml);

$c = count($data['Domain']);
for($i = 0; $i < $c; $i++)
{
  echo $data['Domain'][$i], PHP_EOL;
  echo array_key_exists($data['Code'][$i], $responses) ? $responses[$data['Code'][$i]] : 'I have no idea', PHP_EOL;
}

Output

example.com
This domain is not avaliable.
example.net
This domain is avaliable.
example.org
This domain is not avaliable.

Upvotes: 1

Related Questions