为什么不将这些值作为字符串添加到我的数组中? [英] Why aren't these values being added to my array as strings?
问题描述
在我的问题后面此处 ,实际上我想知道为什么我不使用以下代码将字符串添加到数组中。
Further to my question here, I'm actually wondering why I'm not getting strings added to my array with the following code.
我是从外部来源获取一些HTML的:
I get some HTML from an external source with this:
$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
)
)
...
)
然后我使用以下命令将源添加到数组中:
Then I added the sources to my array with:
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']
是否不视为字符串?
Why isn't $i['src']
treated as a string? Isn't the original [src] element noted where I print $images a string inside there?
换句话说,$ images [0]是一个SimpleXMLElement,我不是在原始的[src]元素中打印了其中的字符串吗?明白。但是为什么当我引用该对象时,那个对象的'src'属性不是作为字符串而是出现在$ sources中 $ i ['src']
?
To put it another way $images[0] is a SimpleXMLElement, I understand that. But why is the 'src' attribute of THAT object not being but into $sources as a string when I reference it as $i['src']
?
推荐答案
为什么$ i ['src']不被视为字符串?
Why isn't $i['src'] treated as a string?
因为它不是一个-这是一个SimpleXMLElement对象,如果使用,它会被 cast 转换为字符串
Becaue it isn't one - it's a SimpleXMLElement object that gets cast to a string if used in a string context, but it still remains a SimpleXMLElement at heart.
要使其成为真实的字符串,请强制将其强制转换为字符串:
To make it a real string, force cast it:
array_push($sources, (string) $i['src']);
这篇关于为什么不将这些值作为字符串添加到我的数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!