用php读取xml文件

KMC*_*KMC 6 php xml

我有一个这种格式的XML文件

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

      </currencies>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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

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

Pri*_*rix 11

使用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";
}
?>
Run Code Online (Sandbox Code Playgroud)

现场演示.

使用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";
}
?>
Run Code Online (Sandbox Code Playgroud)

现场演示.