我正在使用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;
?>
答案 0 :(得分:1)
如果你不想处理糟糕的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.