9

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

 "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 Object ([currency] => SimpleXMLElement Object ([@attributes] => Array ([name] => US Dollar [code_alpha] => USD [code_numeric] => 840)) 的输出

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

4

2 回答 2

18

使用 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:

<?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";
}
?>

现场演示。

于 2013-07-29T06:53:48.023 回答
1

您可以使用 DomDocument 来实现此目标。

检查这篇文章http://www.developersnote.com/2013/12/how-to-read-xml-file-in-php.html

$objDOM = new DOMDocument();

//Load xml file into DOMDocument variable
$objDOM->load("../configuration.xml");

//Find Tag element "config" and return the element to variable $node
$node = $objDOM->getElementsByTagName("config");

//looping if tag config have more than one
foreach ($node as $searchNode) {
    $dbHost = $searchNode->getAttribute('host');
    $dbUser = $searchNode->getAttribute('userdb');
    $dbPass = $searchNode->getAttribute('dbpass');
    $dbDatabase = $searchNode->getAttribute('database');
}
于 2014-01-22T08:21:55.853 回答