首页 > 解决方案 > 未从 XML 获取完整数据

问题描述

我正在使用 simplexml_load_file 函数通过 XML 获取数据。我需要获取 web_remarks 数据。如果我使用 file_get_contents 则此数据将显示在检查元素中。

[Web_Remarks] => SimpleXMLElement Object


                   (
                    )

这两个功能我都试过了。

$xml = simplexml_load_file('http://xml.propspace.com/feed/xml.php?cl=1327&pid=8782&acc=8781');

$result = file_get_contents('http://xml.propspace.com/feed/xml.php?cl=1327&pid=8782&acc=8781');

我只需要得到这个 web_remarks 数据。谢谢你

标签: phphtml

解决方案


在 PHP 中处理 XML 响应的最简单方法是恕我直言,将其转换为数组。您可以使用andsimplexml_load_file($path)或结合使用file_get_contents($path)and simplexml_load_string($content)。我更喜欢后者,因为它首先下载内容,如果发生错误,我仍然可以使用返回的内容。如果返回了有效的 XML,一个简单的转换是通过将其转换为 JSON 然后对其进行解码来使用轻微的绕道。之后,它是一个可以使用的简单数组:

<?php
$file= 'http://xml.propspace.com/feed/xml.php?cl=1327&pid=8782&acc=8781';

$fileContent= file_get_contents($file);
try {
    $xml= simplexml_load_string($fileContent);
    $json = json_encode($xml);
    $array = json_decode($json,TRUE);

    print "<h2>Sample output</h3>".
      "Ad Type of Item 1 in 'Listing': " . $array["Listing"][0]["Ad_Type"]."<br />".
      "Title: <i>" . $array["Listing"][0]["Property_Title"]."</i><br />";


} catch (Exception $ex) {
    print "An exception occurred: " . $ex->getMessage();
}

这将在我的机器上为我提供以下输出:

样本输出


推荐阅读