2


我正在尝试用 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 吗?

感谢所有回复

4

1 回答 1

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";
}

希望这可以帮助。

于 2012-03-22T14:26:28.387 回答