0

I have this Xml file https://www.cba.am/_layouts/rssreader.aspx?rss=280F57B8-763C-4EE4-90E0-8136C13E47DA and I want to read same specific colums, there are currency online rates and want to read only the 3 of them, how can I do that with php? I try this but with no results

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

foreach($xml -> item as $item){
    echo $item[0];
}
?>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Arturik1988
  • 103
  • 2
  • 13
  • 1
    Since the XML in question is an RSS feed, see [this existing question](http://stackoverflow.com/q/250679/157957) for lots of tips. Your specific mistake is that the `item` elements are inside the `channel` element, so you need `foreach ( $xml->channel->item as $item )`, and then `echo $item->description` etc to get the description text of each. – IMSoP Oct 26 '13 at 17:06

1 Answers1

0

You want the title elements in the first three item elements. This is a typical job for Xpath which is supported by Simplexml. Such a kind of Xpath 1.0 expression would fulfill your needs:

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

A code-example then is:

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

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

The output in your case is (as of some minutes ago):

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

I'd say using Xpath here is most sane, no need for an external library.

The full code-example including caching and error handling as I did it quickly:

<?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";
}
hakre
  • 193,403
  • 52
  • 435
  • 836