2

我有一个如下的 XML 文件:

<subject KL="1">
    <subjectName>If-Else</subjectName>
    <theory>
       <tutorial>...</tutorial>
       <full>...</full>
    </theory>
</subject>

我尝试使用以下 PHP 代码提取它:

$subjects = $doc->getElementsByTagName( "subject" );
foreach( $subjects as $subject ) {
      $knowledgeLevel = $subject->getAttribute( "KL" );
      $names = $subject->getElementsByTagName( "subjectName" );
      $name = $names->item(0)->nodeValue;

      $theory = $subject->getElementsByTagName( "theory" );
      $shorts = $theory->getElementsByTagName( "tutorial" );
      $short = $shorts->item(0)->nodeValue;
      $longs = $theory->getElementsByTagName( "full" );
      $long = $longs->item(0)->nodeValue;

      $subs [] = array (
            'knowledgeLevel' => $knowledgeLevel,
            'name' => $name,
            'shortTheory' => $short,
            'longTheory' => $long
      );
}

但我的浏览器给了我错误

Call to undefined method DOMNodeList::getElementsByTagName()

在代码片段的第 8 行。我不明白为什么它不应该工作。有什么帮助吗?

4

2 回答 2

4

使用 getElementsByTagName 的示例

$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<subject KL="1">
    <subjectName>If-Else</subjectName>
    <theory>
       <tutorial>...</tutorial>
       <full>...</full>
    </theory>
</subject>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('subject');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}

在你的循环中试试这个

$theory = $subject->getElementsByTagName( "theory" );
$tutorial = $theory->item(0)->getElementsByTagName( "tutorial" )->item(0)->nodeValue;
于 2013-05-06T09:43:03.733 回答
3

但是 DOMNodeList 没有那个方法。

getElementsByTagName是 DOMDocument 类的一部分

于 2013-05-06T09:38:30.690 回答