我的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行。我不明白为什么它不应该工作。有什么帮助吗?
答案 0 :(得分:3)
使用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;
答案 1 :(得分:2)
但是DOMNodeList没有那种方法。
getElementsByTagName
是DOMDocument类的一部分