php - 调用未定义的方法 DOMNodeList::getElementsByTagName() PHP

标签 php xml

我有一个如下所示的 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 行。我不明白为什么它不起作用。有帮助吗?

最佳答案

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

关于php - 调用未定义的方法 DOMNodeList::getElementsByTagName() PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16395826/

相关文章:

php - 如何在laravel中选择特定的列

php - Else 语句在选项选择中不起作用

python - 使用 xml.etree.ElementTree 获取子节点的所有实例

php - codeigniter 在 session 中设置多维数组

基于 PHP 的游戏 - 为每个用户提供自己的数据库

java - 简单的命令行 xquery

android - <uses-permission> 元素必须是 <manifest> 根元素的直接子元素

php - 由于 xml 错误,soap php 调用出现问题

java - Install4j 使用正则表达式和 xpath 表达式更新 XML 文件

PHP扩展库依赖