为什么这些值没有作为字符串添加到我的数组中?
关于我的问题这里,我'我实际上想知道为什么我没有使用以下代码将字符串添加到我的数组中。
我通过以下方式从外部源获取一些 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 ']
被视为字符串?我在其中打印 $images 字符串的地方是否没有注意到原始的 [src] 元素?
换句话说,$images[0] 是一个 SimpleXMLElement,我明白这一点。但是当我将其引用为 $i['src']
时,为什么该对象的“src”属性不是作为字符串而是作为字符串放入 $sources 中?
Further to my question here, I'm actually wondering why I'm not getting strings added to my array with the following code.
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();
Here is the images 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']);
}
But when I print the results:
echo "<pre>";
print_r($sources);
die();
I get this:
Array
(
[0] => SimpleXMLElement Object
(
[0] => http://www.domain.com/someimages.jpg
)
...
)
Why isn't $i['src']
treated as a string? Isn't the original [src] element noted where I print $images a string inside there?
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']
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为它不是一个 - 它是一个 SimpleXMLElement 对象,如果在字符串上下文中使用,它会转换为字符串,但它本质上仍然是一个 SimpleXMLElement。
要使其成为真正的字符串,请强制转换它:
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:
因为
SimpleXMLElement::xpath()
< /strong> (引用):而不是字符串数组。
So, the items of your `$images` array are `SimpleXMLElement` objects, and not strings -- which is why you have to cast them to strings, if you want strings.
Because
SimpleXMLElement::xpath()
(quoting) :and not an array of strings.
So, the items of your `$images` array are `SimpleXMLElement` objects, and not strings -- which is why you have to cast them to strings, if you want strings.