【问题标题】:Problems accessing sections of Array from XML response从 XML 响应访问 Array 部分的问题
【发布时间】:2017-07-31 08:01:58
【问题描述】:

我正在发送一个 XML URL 以返回一些我已设法显示为多个数组的数据。我发现很难分离一些特定数据,并希望有人能够通过示例教我如何将这些数据正确添加到变量中。

这是使用print_r();的完整数组

SimpleXMLElement Object ( [@attributes] => Array ( [Status] => OK ) [Errors] => SimpleXMLElement Object ( ) [Warnings] => SimpleXMLElement Object ( ) [RequestedCommand] => namecheap.domains.check [CommandResponse] => SimpleXMLElement Object ( [@attributes] => Array ( [Type] => namecheap.domains.check ) [DomainCheckResult] => SimpleXMLElement Object ( [@attributes] => Array ( [Domain] => test.com [Available] => false [ErrorNo] => 0 [Description] => [IsPremiumName] => false [PremiumRegistrationPrice] => 0 [PremiumRenewalPrice] => 0 [PremiumRestorePrice] => 0 [PremiumTransferPrice] => 0 [IcannFee] => 0 [EapFee] => 0 ) ) ) [Server] => PHX01APIEXT01 [GMTTimeDifference] => --4:00 [ExecutionTime] => 0.045 ) 

我通常可以很好地管理数组,尽管这里的“@attributes”让我感到困惑...这是我目前的脚本(请记住,我只是在这里进行测试)。

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

echo '<br><br>';

$status = current($xml->attributes());
$results = $xml->DomainCheckResult->attributes();
echo $status['Status'];
echo '<br><br>';

print_r($results);

$status 变量正在工作并回显“OK”。 $results 变量似乎只显示“SimpleXMLElement Object ()”

我正在尝试专门针对这些 -

 [Domain] => test.com [Available] => false [ErrorNo] => 0 [Description] => [IsPremiumName] => false [PremiumRegistrationPrice] => 0 [PremiumRenewalPrice] => 0 [PremiumRestorePrice] => 0 [PremiumTransferPrice] => 0 [IcannFee] => 0 [EapFee] => 0

但我似乎无法比现在更进一步?我将如何使用这些数据来获得类似于以下内容...

$domain_req = $xml[Domain];
$domain_avail = $xml[Available];

等等……?

根据要求,这里是原始 XML -

<ApiResponse xmlns="http://api.namecheap.com/xml.response" Status="OK">
<Errors/>
<Warnings/>
<RequestedCommand>namecheap.domains.check</RequestedCommand>
<CommandResponse Type="namecheap.domains.check">
<DomainCheckResult Domain="test.com" Available="false" ErrorNo="0" Description="" IsPremiumName="false" PremiumRegistrationPrice="0" PremiumRenewalPrice="0" PremiumRestorePrice="0" PremiumTransferPrice="0" IcannFee="0" EapFee="0"/>
</CommandResponse>
<Server>PHX01APIEXT03</Server>
<GMTTimeDifference>--4:00</GMTTimeDifference>
<ExecutionTime>0.018</ExecutionTime>
</ApiResponse>

【问题讨论】:

  • 能否显示原始 XML 而不是输出或print_r
  • @NigelRen 我已经更新了我的问题

标签: php arrays xml


【解决方案1】:

要访问这些,您应该使用...

$status = current($xml->attributes());
$results = $xml->CommandResponse->DomainCheckResult->attributes();
echo $status['Status'];

$domain_req = $results['Domain'];
$domain_avail = $results['Available'];

您必须在名称周围使用引号。

【讨论】:

  • 当我尝试回应这些内容时,我什么也得不到?我不确定我的$results 变量是否设置正确?
  • 我已经更新了答案,它是 $results,它的分层略有不同。 (我也确实错过了结果中的 s)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多