用php读取xml文件 [英] read xml file with php

查看:73
本文介绍了用php读取xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种格式的XML文件

I have an XML file in this format

 "note.xml"
      <currencies>
     <currency name="US dollar" code_alpha="USD" code_numeric="840" />
         <currency name="Euro" code_alpha="EUR" code_numeric="978" />

      </currencies>

PHP代码

$xml=simplexml_load_file("note.xml");

echo $xml->name. "<br>";             --no output
echo $xml->code_alpha. "<br>";        --no output
echo $xml->code_numeric . "<br>";        --no output

     print_r($xml);

print_r($ xml)的输出-> SimpleXMLElement对象([currency] => SimpleXMLElement对象([@attributes] =>数组([name] =>美元[code_alpha] => USD [code_numeric] => 840))

output of print_r($xml)-->SimpleXMLElement Object ( [currency] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => US dollar [code_alpha] => USD [code_numeric] => 840 ) )

我没有得到ECHO语句的任何输出 我尝试了'simplexml_load_file'并尝试从中读取,但是它不起作用.请告诉我应该使用什么php代码从这种格式的XML文件读取.

I didnt get any output for the ECHO statements I tried 'simplexml_load_file' and tried reading from it but it doesnt work. Please tell me what php code should I use to read from this format of XML file.

推荐答案

使用DomDocument:

Using DomDocument:

<?php
$str = <<<XML
<currencies>
    <currency name="US dollar" code_alpha="USD" code_numeric="840" />
    <currency name="Euro" code_alpha="EUR" code_numeric="978" />
</currencies>
XML;

$dom = new DOMDocument();
$dom->loadXML($str);

foreach($dom->getElementsByTagName('currency') as $currency)
{
    echo $currency->getAttribute('name'), "\n";
    echo $currency->getAttribute('code_alpha'), "\n";
    echo $currency->getAttribute('code_numeric'), "\n";
    echo "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n";
}
?>

实时演示.

使用simplexml:

Using simplexml:

<?php
$str = <<<XML
<currencies>
    <currency name="US dollar" code_alpha="USD" code_numeric="840" />
    <currency name="Euro" code_alpha="EUR" code_numeric="978" />
</currencies>
XML;


$currencies = new SimpleXMLElement($str);
foreach($currencies as $currency)
{
    echo $currency['name'], "\n";
    echo $currency['code_alpha'], "\n";
    echo $currency['code_numeric'], "\n";
    echo "+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+\n";
}
?>

实时演示.

Live DEMO.

这篇关于用php读取xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆