我如何重写这个PHP函数从外部网站/源提取数据



我有这个PHP函数,从xml元素中提取数据,并在我的网页上显示它们。然而,它只在与本地路径一起使用时才有效。不是来自任何外部资源。代码如下:

index . php

<html>
<body>
<?php
    include('render_xml_to_html.php');
    // The internal path. DOES work.
    render_xml_data('example.xml');
?>
</body>
</html>

Example.xml

<eveapi version="2"><currentTime>2014-05-08 03:34:23</currentTime>
    <result>
        <serverOpen>True</serverOpen>
        <onlinePlayers>24957</onlinePlayers>
    </result>
    <cachedUntil>2014-05-08 03:35:58</cachedUntil>
</eveapi>

函数- render_xml_to_html.php

<?php
function render_xml_data($path_to_xml_file){
        if (!file_exists($path_to_xml_file)){
            return;
        }else{
            $chars_to_replace = array('[r]','[n]','[t]');
            $xmlstring = trim(preg_replace($chars_to_replace, '', file_get_contents($path_to_xml_file)));
        }
        $xml = new SimpleXMLElement($xmlstring);
        foreach ($xml->result as $record) {
            echo '<div class="record">'."n";
            echo '<h3>'.$record->onlinePlayers.'</h3>'."n";
            echo '</div><!--end record-->'."n";
        }
    }
?>

以上代码按原样工作。我的问题是,当我试图从主机服务器上的实时.xml文件拉这个信息。url是:

https://api.eveonline.com/server/ServerStatus.xml.aspx/

当我用上面的链接替换example.xml时,它无法工作。所以下面的方法行不通。链接到外部路径,而不是本地路径。

<?php
    include('render_xml_to_html.php');
    // The external path DOES NOT WORK
    render_xml_data('https://api.eveonline.com/server/ServerStatus.xml.aspx/');
?>

提前感谢!

您可以在这个上面使用file_get_contents,它可以完成工作。考虑这个例子:

$url = 'https://api.eveonline.com/server/ServerStatus.xml.aspx/';
// access the url and get that file
$contents = file_get_contents($url);
// convert it to an xml object
$contents = simplexml_load_string($contents);
echo "<div class='record'>Number of Online Players: ".$contents->result->onlinePlayers."</div>";

样本输出:

在线玩家数:23893

最新更新