【问题标题】:PHP DomParser getting option name and value from xml tagPHP DomParser 从 xml 标签获取选项名称和值
【发布时间】:2012-03-22 13:56:22
【问题描述】:


我正在尝试使用 PHP 解析 xml 文件。
我正在使用这段代码,它可以很好地获取标记名和值:

函数 getChildNodes($dom,$SearchKey){

  foreach ($dom->getElementsByTagName($SearchKey) as $telefon) {
      foreach($telefon->childNodes as $node) {
          print_r(
          $SearchKey . " : " . $node->nodeValue . "\n"                
      );
  }

} }

工作代码的示例xml:

<inputs>
 <input>C:\Program Files\VideoLAN\VLC\airbag.mp3</input>
 <input>C:\Program Files\VideoLAN\VLC\sunpark.mp3</input>
 <input>C:\Program Files\VideoLAN\VLC\rapidarc.mp3</input>
</inputs>

无效代码的示例 xml:

<instances>
 <instance name="default" state="playing" position="0.050015" time="9290569" length="186489519" rate="1.000000" title="0" chapter="0" can-seek="1" playlistindex="3"/>
</instances>

谁能帮我弄清楚我需要使用哪些选项来获取 optioname 和 optionvalue?

感谢所有回复

【问题讨论】:

    标签: php xml xml-parsing domparser


    【解决方案1】:

    这是一个打印出 XML 属性的代码示例:

    <?php
    
    $source = '<instances><instance name="default" state="playing" position="0.050015" time="9290569" length="186489519" rate="1.000000" title="0" chapter="0" can-seek="1" playlistindex="3"/></instances>';
    
    $doc = new DOMDocument();
    $doc->loadXML($source);
    
    $el = $doc->firstChild->firstChild;
    
    for ($i = 0; $i < $el->attributes->length; $i++) {
        $attr = $el->attributes->item($i);
        echo 'Name: '.$attr->name, "\n";
        echo 'Value: '.$attr->value, "\n";
    }
    

    希望这会有所帮助。

    【讨论】:

    • 谢谢!我正在寻找 $attr->name 和 $attr->value
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多