【问题标题】:Why am I getting an array of SimpleXMLElement Objects here?为什么我在这里得到一组 SimpleXMLElement 对象?
【发布时间】: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


    【解决方案1】:

    差异不是由array_push() 引起的——而是由您在第二种情况下使用的类型转换


    在您的第一个循环中,您正在使用:

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

    这意味着您正在将SimpleXMLElement 对象添加到您的数组中。


    而在第二个循环中,您正在使用:

    $sources[] = (string)$i['src'];
    

    这意味着 (感谢强制转换为字符串)您正在向数组中添加字符串——而不是 SimpleXMLElement 对象了。


    作为参考:手册的相关部分:Type Casting.

    【讨论】:

    • 谢谢 - 如果你好心,我已经发布了一个后续问题。我更想知道我什么时候不投,我没有添加字符串。
    【解决方案2】:

    抱歉,刚刚注意到上面有更好的答案,但正则表达式本身仍然有效。 您是否尝试获取 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);
                    }
    
            }
    

    【讨论】:

      【解决方案3】:

      在您的第一个示例中,您应该:

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

      您的第二个示例提供了一个字符串数组,因为您正在使用 (string) 强制转换将 SimpleXMLElements 转换为字符串。在你的第一个例子中你不是,所以你得到一个 SimpleXMLElements 数组。

      【讨论】:

        猜你喜欢
        • 2020-07-31
        • 2021-11-08
        • 2016-11-22
        • 2015-10-25
        • 1970-01-01
        • 2016-09-26
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多