在PHP中读取Xml文件

时间:2013-10-26 16:54:44

标签: php xml

我有这个Xml文件https://www.cba.am/_layouts/rssreader.aspx?rss=280F57B8-763C-4EE4-90E0-8136C13E47DA,我想阅读相同的特定列,有货币在线费率,并且只想阅读其中的3个,我怎么能用PHP做到这一点?我试试这个但没有结果

<?php
$file = "feed.xml";
$xml = simplexml_load_file($file);

foreach($xml -> item as $item){
    echo $item[0];
}
?>

1 个答案:

答案 0 :(得分:0)

您需要前三个title元素中的item元素。这是Xpath支持Simplexml的典型作业。这种Xpath 1.0表达式可满足您的需求:

//item[position() < 4]/title

然后是代码示例:

$titles = $xml->xpath('//item[position() < 4]/title');

foreach ($titles as $title)
{
    echo $title, "\n";
}

您的案例中的输出是(截至几分钟前):

USD - 1 - 405.8400
GBP - 1 - 657.4200
AUD - 1 - 389.5700

我说在这里使用Xpath是最理智的,不需要外部库。

完整的代码示例包括缓存和错误处理,因为我快速完成了:

<?php
/**
 * Reading Xml File
 *
 * @link http://stackoverflow.com/q/19609309/367456
 */

$file = "feed.xml";

if (!file_exists($file))
{
    $url    = 'https://www.cba.am/_layouts/rssreader.aspx?rss=280F57B8-763C-4EE4-90E0-8136C13E47DA';
    $handle = fopen($url, 'r');
    file_put_contents($file, $handle);
    fclose($handle);
}

$xml = simplexml_load_file($file);

if (!$xml)
{
    throw new UnexpectedValueException('Failed to parse XML data');
}
$titles = $xml->xpath('//item[position() < 4]/title');

foreach ($titles as $title)
{
    echo $title, "\n";
}