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条)

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch