我有一个这种格式的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)的输出 - &gt; SimpleXMLElement对象([货币] =&gt; SimpleXMLElement对象([@属性] =&gt;数组([名称] =&gt;美元[code_alpha] =&gt; USD [code_numeric] =&gt; 840))
我没有获得ECHO声明的任何输出 我试过'simplexml_load_file'并尝试从中读取但它不起作用。请告诉我应该用什么PHP代码来读取这种格式的XML文件。
答案 0 :(得分:10)
使用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";
}
?>
<强> Live DEMO. 强>
答案 1 :(得分:0)
您可以使用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');
}