为什么我在这里得到一个SimpleXMLElement对象数组?

| 我有一些代码可以从外部来源获取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对象而不是字符串。我知道在显式转换为字符串时会得到一个字符串。请参阅此处的后续问题:为什么不将这些值作为字符串添加到我的数组中?     
已邀请:
差异不是由ѭ5引起的-而是在第二种情况下使用的类型转换。 在您的第一个循环中,您正在使用:
array_push($sources, $i[\'src\']);
这意味着您要向数组中添加“ 7”个对象。 在第二个循环中,您正在使用:
$sources[] = (string)$i[\'src\'];
这意味着(由于强制转换为字符串),意味着您正在将字符串添加到数组中-不再是“ 7”个对象。 作为参考:手册的相关部分:铸造。     
抱歉,刚才注意到更好的答案,但是正则表达式本身仍然有效。 您是否要获取HTML标记中的所有图像? 我知道您正在使用PHP,但是您可以使用下面的C#示例进行转换:
List<string> links = new List<string>();
            if (!string.IsNullOrEmpty(htmlSource))
            {
                string regexImgSrc = @\"<img[^>]*?src\\s*=\\s*[\"\"\']?([^\'\"\" >]+?)[ \'\"\"][^>]*?>\";
                MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                foreach (Match m in matchesImgSrc)
                {
                    string href = m.Groups[1].Value;
                    links.Add(href);
                }

        }
    
在第一个示例中,您应该:
array_push($sources, (string) $i[\'src\']);
第二个示例提供了一个字符串数组,因为您正在使用
(string)
强制转换将SimpleXMLElements转换为字符串。在第一个示例中,您并非如此,因此您将获得一个SimpleXMLElements数组。     

要回复问题请先登录注册