【问题标题】:invalid argument supplied for foreach为 foreach 提供的参数无效
【发布时间】:2011-05-17 18:58:18
【问题描述】:

我在 PHP 代码中解析 XML 并收到警告“为 foreach 提供的参数无效”。 以下是 XML:

<?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

【问题讨论】:

  • 标签之间的空格会生成一个文本节点。

标签: php xml


【解决方案1】:
foreach ($document->childNodes as $node) {
    if ($node->hasChildNodes()) {
        foreach($node->childNodes as $temp) {
            echo $temp->nodeName."=".$temp->nodeValue."<br />";
        }
    }
}

【讨论】:

  • 谢谢,但我想知道 $node 中的空节点是如何出现的,因为它似乎只有两个“书”节点。我可以清零吗?谢谢。
  • 空格,即回车/换行也是子元素。它们是文本节点。
【解决方案2】:

您正尝试在 book 部分之前和之后迭代文本节点。

【讨论】:

    【解决方案3】:

    不确定 xml 是如何工作的,但这个错误是你的 foreach 中的第一个 $variable 不是数组的类。因为函数只能分解数组。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      相关资源
      最近更新 更多