API 的 XML PHP 解析问题


Issues with API's XML PHP parsing

我正在使用API,但是他们设置返回的XML的方式不正确,因此我需要提出解析它的解决方案。 我无法转换为 JSON(我首选的返回方法),因为他们不支持它。下面我列出了我的XML和PHP。

API 返回的 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>

每个代码都适用于以前的域。我不知道如何将这两者联系在一起,并且仍然能够循环访问返回的所有结果。基本上每个顶级域都会返回一个域和一个代码,因此结果很多。

到目前为止的PHP代码:

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

如果你不想处理蹩脚的XML(我并不是说XML一般都很糟糕,但这个是),你可以考虑这样的事情:

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

输出

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