【发布时间】:2011-04-14 18:03:45
【问题描述】:
我有一些从外部源提取 HTML 的代码:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xml = @simplexml_import_dom($doc); // just to make xpath more simple
$images = $xml->xpath('//img');
$sources = array();
然后,如果我使用此代码添加所有来源:
foreach ($images as $i) {
array_push($sources, $i['src']);
}
echo "<pre>";
print_r($sources);
die();
我得到这个结果:
Array
(
[0] => SimpleXMLElement Object
(
[0] => /images/someimage.gif
)
[1] => SimpleXMLElement Object
(
[0] => /images/en/someother.jpg
)
....
)
但是当我使用这段代码时:
foreach ($images as $i) {
$sources[] = (string)$i['src'];
}
我得到了这个结果(这是想要的):
Array
(
[0] => /images/someimage.gif
[1] => /images/en/someother.jpg
...
)
造成这种差异的原因是什么? array_push() 有什么不同?
谢谢,
编辑:虽然我意识到答案与我的要求相符(我已经授予),但我更想知道为什么使用 array_push 或其他表示法添加 SimpleXMLElement 对象而不是字符串时两者都没有铸造。我知道当显式转换为字符串时,我会得到一个字符串。在此处查看后续问题:Why aren't these values being added to my array as strings?
【问题讨论】:
标签: php arrays simplexml domdocument