你想在前三item
元素title
元素。這是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";
}
由於有關XML是一個RSS feed,請參閱[這個存在的問題(http://stackoverflow.com/q/250679/157957)提供了很多提示。你的具體錯誤是'item'元素在'channel'元素中,所以你需要'foreach($ xml-> channel-> item作爲$ item)',然後'echo $ item-> description'等獲取每個的描述文本。 – IMSoP