【问题标题】:XML file to PHP array (w/attributes)XML 文件到 PHP 数组(带属性)
【发布时间】:2011-05-27 22:29:33
【问题描述】:

我以前没有真正使用过 xml 文件,但现在我正在尝试将 xml 文件放入 php 数组或对象中。 xml 文件如下所示:(用于翻译网络应用)

<?xml version="1.0" ?>
<content language="de"> 
 <string name="login">Login</string>
 <string name="username">Benutzername</string>
 <string name="password">Passwort</string>
</content>

我尝试了以下方法:

$xml = new SimpleXMLElement("de.xml", 0, 1);
print_r($xml);

不幸的是,'name' 属性的值由于某种原因不在 php 对象中。我正在寻找一种允许我通过 name 属性检索 xml 值的方法。

例如:

$xml['username'] //returns "Benutzername"

如何做到这一点? 感谢您的帮助 :) 干杯!

【问题讨论】:

    标签: php xml object


    【解决方案1】:

    这个应该给你解释一下功能:

    <?php
    $xml = simplexml_load_file('de.xml');
    
    foreach($xml->string as $string) { 
      echo 'attributes: '. $string->attributes() .'<br />';
    }
    ?>
    

    SimpleXMLElement 类中的 attributes() 方法将帮助您 - http://de.php.net/manual/en/simplexmlelement.attributes.php

    【讨论】:

      【解决方案2】:
      $xmlStr = <<<XML
      <?xml version="1.0" ?>
      <content language="de"> 
       <string name="login">Login</string>
       <string name="username">Benutzername</string>
       <string name="password">Passwort</string>
      </content>
      XML;
      
      $doc = new DomDocument();
      $doc->loadXML($xmlStr);
      
      $strings = $doc->getElementsByTagName('string');
      foreach ($strings as $node) {
          echo $node->getAttribute('name') . ' = ' . $node->nodeValue . PHP_EOL;
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用 xpath 表达式来获取具有您要查找的名称的元素:

        (string)current($xml->xpath('/content/string[@name="username"]'))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 1970-01-01
          • 2014-10-20
          • 2022-08-15
          • 2021-11-12
          • 1970-01-01
          相关资源
          最近更新 更多