【问题标题】:read xml file with php用php读取xml文件
【发布时间】:2013-07-29 06:43:46
【问题描述】:

我有一个这种格式的 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] => 美元 [code_alpha] => USD [code_numeric] =>第840章)

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

【问题讨论】:

  • 你为什么说simplexml_load_file没用?首先向我们展示您的 php 代码。
  • echo $xml-&gt;name. "&lt;br&gt;"; echo $xml-&gt;code_alpha . "&lt;br&gt;"; echo $xml-&gt;code_numeric. "&lt;br&gt;"; 我按照 W3schools 尝试过,但输出为空白.....
  • 永远不要再咨询 w3schools。这通常是错误的和误导性的。

标签: php xml


【解决方案1】:

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

Live DEMO.

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

【讨论】:

    【解决方案2】:

    您可以使用 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');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2014-05-06
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多