2010-11-30 13 views
0

PHPコードでXMLを解析していて、 "foreachで無効な引数が指定されました"という警告が表示されています。以下 はXMLです:foreachの引数が無効です

<?xml version="1.0" encoding="ISO-8859-1"?> 
<BookStore> 
    <book> 
     <title>Computer Concepts</title> 
     <auther>Goerge Arthar</auther> 
     <category>Computer Science</category> 
     <price>24.00</price> 
    </book> 
    <book> 
     <title>Algebra</title> 
     <auther>Mike</auther> 
     <category>Mathematics</category> 
     <price>34.00</price> 
    </book> 
</BookStore> 

と次のコードを使用して:

<?php 
$xmlDOM = new DOMDocument(); 
$xmlDOM->load("Books.xml"); 
$document = $xmlDOM->documentElement; 
foreach ($document->childNodes as $node) { 
    foreach($node->childNodes as $temp) { 
     echo $temp->nodeName."=".$temp->nodeValue."<br />"; 
    } 
} 
?> 

注:私は、私は必要な出力が得られますが、警告で。配列が空でないことを示します。 はまた、出力を参照してください。

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8 
#text= 
title=Computer Concepts 
#text= 
auther=Goerge Arthar 
#text= 
category=Computer Science 
#text= 
price=24.00 
#text= 

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8 
#text= 
title=Algebra 
#text= 
auther=Mike 
#text= 
category=Mathematics 
#text= 
price=34.00 
#text= 

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8 
+0

タグ間の空白がtextnodeを生成します。 – mario

答えて

0
foreach ($document->childNodes as $node) { 
    if ($node->hasChildNodes()) { 
     foreach($node->childNodes as $temp) { 
      echo $temp->nodeName."=".$temp->nodeValue."<br />"; 
     } 
    } 
} 
+0

ありがとうございます。しかし、2つの 'book'ノードだけを持つように見えるので、空ノードは$ nodeにどのように表示されるのでしょうか。私はクリアすることができますか? ありがとうございます。 –

+0

空白、つまり改行/改行も子要素です。テキストノードです。 – stillstanding

0

あなたはbookセクションの前と後のテキストノードを反復処理しようとしています。

0

xmlの仕組みは分かりませんが、このエラーはforeach内の最初の$変数が配列ではないクラスです。関数は配列を分解することしかできません。

関連する問題