【问题标题】:For loop while parsing xml in php?在php中解析xml时for循环?
【发布时间】:2012-02-21 09:48:30
【问题描述】:

我正在尝试创建一个 for 循环,它将使用 php 解析出 xml doc 的不同元素。当我将条目的编号放入该行时,它会解析:

$s = $xml->entry[0]->children($namespaces['s']); 

但是,我尝试将数字替换为“i”以计算 xml 文档中的每个条目,但出现错误(致命错误:在 /home 中的非对象上调用成员函数 children() /content/c/a/s/cashme/html/buylooper/xml.php 在第 10 行)。我该如何解决这个问题?

<?php
$url = 'xml-file.xml'; 
$xml = simplexml_load_file($url); 
$namespaces = $xml->entry->getNameSpaces(true); 

for ($i = 0; $i <= 10; $i += 1){

$s = $xml->entry[i]->children($namespaces['s']); 
$title = $s->product->title; 

//print 
echo $retailer;

}
?>

【问题讨论】:

  • 这意味着对于i 的某些值,$xml-&gt;entry[i] 不存在。
  • @Ben:将其发布为答案,以便 sharataka 可以接受。

标签: php xml loops for-loop


【解决方案1】:

您需要使用 $i,而不是 i。

附注:

这个错误应该在开发机器上变得非常明显:

你会收到类似Use of undefined constant i - assumed 'i'的警告

(除非您在某处将 i 定义为常量,但这是一个奇怪的常量名称)

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 2013-11-22
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多