dpp42324 2010-04-20 01:13
浏览 73
已采纳

PHP:SimpleXML和Arrays

When I run this code:

foreach($xml->movie as $movie) { 
    if(isset($movie->photos)) { 
        foreach ($movie->photos as $photo) { 
            echo $photo." "; 
        } 
        echo "<hr/>"; 
    }
}

I get nice output of the actual data, e.g. a row looks like

06397001.jpg 06397002.jpg 06397003.jpg 06397004.jpg 06397005.jpg

But when I throw it in an array, it includes all the SimpleXML wrapper tags and the jpgs are not at the root of the array.

code:

foreach($xml->movie as $movie) { 
    if(isset($movie->photos)) { 
        $photos = array(); 
            foreach ($movie->photos as $photo) { 
                $photos[] = $photo; 
            } 
    } else $photos = ""; 
    var_dump($photos); 
    echo "<hr />"; 
}

e.g. same row looks like

array(5) { 
    [0]=> object(SimpleXMLElement)#11 (1) { 
        [0]=> string(12) "06397001.jpg" 
    }
    [1]=> object(SimpleXMLElement)#12 (1) {
        [0]=> string(12) "06397002.jpg" 
    } 
    [2]=> object(SimpleXMLElement)#13 (1) {
        [0]=> string(12) "06397003.jpg"
    }
    [3]=> object(SimpleXMLElement)#14 (1) {
        [0]=> string(12) "06397004.jpg"
    }
    [4]=> object(SimpleXMLElement)#15 (1) {
        [0]=> string(12) "06397005.jpg"
    }
}

Why is this happening/how can I remove this so I just get an array of the photos at root level like when I echo it?

  • 写回答

2条回答 默认 最新

  • doudai8783 2010-04-20 02:44
    关注

    SimpleXMLElement results look like simple objects and arrays, but do some magical things that normal objects and arrays can't do. It's designed this way so that you can use less code.

    You can probably solve your problem with something like:

    foreach($xml->movie as $movie) { 
      if(isset($movie->photos)) {
        $photos = array();
        foreach ($movie->photos as $photo) {
          $photos[] = "$photo"; 
          // or you could use, I believe: $photos[] = $photo[0] 
        }
      } 
      else $photos = "";
      var_dump($photos); echo "<hr />";
    }
    

    Why is this happening? Because a SimpleXML element when treated as a string will behave as if it's a string, with the value being that element's text contents. In your first example, the use of echo was treating the element as a string so it just returned the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里