PHP:SimpleXML的和数组 [英] PHP: SimpleXML and Arrays

查看:190
本文介绍了PHP:SimpleXML的和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行这个code:

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

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

但是,当我在一个数组扔,它包括所有的包装的SimpleXML标签和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?

推荐答案

的SimpleXMLElement结果看起来简单对象和数组,但做一些神奇的东西,正常的对象和数组不能做。它的设计,这样一来,这样就可以少用code。

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 />";
}

这是怎么回事?因为当视为字符串的行为就好像它是一个字符串,用价值在于元素的文本内容的SimpleXML元素。在你的第一个例子中,使用echo是治疗的元素作为一个字符串,所以它只是返回的字符串。

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.

这篇关于PHP:SimpleXML的和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆