首页 文章

用php读取xml文件

提问于
浏览
6

我有一个这种格式的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对象([currency] => SimpleXMLElement对象([@attributes] =>数组([name] =>美元[code_alpha] => USD [code_numeric] => 840))

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

2 回答

  • 0

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

  • 9

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

相关问题