如何重写此PHP函数以从外部网站/源提取数据

时间:2014-05-08 03:54:38

标签: php xml

我有这个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文件中提取此信息时。那个网址是:

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

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

<?php
    include('render_xml_to_html.php');

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

你可以在这个上使用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

相关问题