为什么不把这些值作为字符串添加到数组中?


Why aren't these values being added to my array as strings?

进一步我的问题在这里,我实际上想知道为什么我没有得到字符串添加到我的数组与以下代码。

我从外部源获得一些HTML:

$doc = new DOMDocument();
@$doc->loadHTML($html);
$xml = @simplexml_import_dom($doc); // just to make xpath more simple
$images = $xml->xpath('//img');
$sources = array(); 

这里是图像数组:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [alt] => techcrunch logo
                    [src] => http://s2.wp.com/wp-content/themes/vip/tctechcrunch/images/logos_small/techcrunch2.png?m=1265111136g
                )
        )
   ...
)

然后我添加源到我的数组:

foreach ($images as $i) {   
  array_push($sources, $i['src']);
} 

但是当我打印结果时:

 echo "<pre>";
 print_r($sources);
 die();

我得到这个:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => http://www.domain.com/someimages.jpg
        )
    ...
)

为什么不将$i['src']视为字符串?原来的[src]元素在我打印$images的地方不是一个字符串吗?

换句话说$images[0]是一个SimpleXMLElement,我理解这一点。但是为什么那个对象的'src'属性不是,而是进入$sources作为字符串,当我引用它为 $i['src'] ?

为什么$i['src']不被视为字符串?

因为它不是一个-它是一个SimpleXMLElement对象,如果在字符串上下文中使用转换为字符串,但它本质上仍然是一个SimpleXMLElement。

要使它成为一个真正的字符串,强制转换它:

array_push($sources, (string) $i['src']);  

, SimpleXMLElement::xpath() (引用):

返回SimpleXMLElement数组对象

而不是字符串数组。


因此,$images数组中的项是SimpleXMLElement对象,而不是字符串——这就是为什么如果您想要字符串,必须将它们强制转换为字符串的原因。