Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP读取Xml文件_Php_Xml - Fatal编程技术网

用PHP读取Xml文件

用PHP读取Xml文件,php,xml,Php,Xml,我有这个Xml文件,我想读相同的特定列,有货币在线汇率,只想读其中的3个,我如何用php做到这一点?我试过了,但是没有结果 <?php $file = "feed.xml"; $xml = simplexml_load_file($file); foreach($xml -> item as $item){ echo $item[0]; } ?> 您希望在前三个项中包含标题元素。这是一个典型的工作,它由支持。这种表达方式可以满足您的需求: //item[positi

我有这个Xml文件,我想读相同的特定列,有货币在线汇率,只想读其中的3个,我如何用php做到这一点?我试过了,但是没有结果

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

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

您希望在前三个
项中包含
标题
元素。这是一个典型的工作,它由支持。这种表达方式可以满足您的需求:

//item[position() < 4]/title
我认为在这里使用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提要,请参阅以获取大量提示。您的具体错误是,
元素位于
频道
元素内,因此您需要
foreach($xml->channel->item as$item)
,然后
echo$item->description
等来获取每个项目的描述文本。
USD - 1 - 405.8400
GBP - 1 - 657.4200
AUD - 1 - 389.5700
<?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";
}