2011-04-14 40 views
3

我有一些代碼,從外部源拉HTML:爲什麼我在這裏獲取一個SimpleXMLElement對象數組?

$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?

回答

3

區別不是由array_push()引起 - 而是由引起的,您在第二種情況下使用


在你的第一個循環,你正在使用:

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

這意味着要添加SimpleXMLElement對象你的陣列。


雖然,在第二循環中,使用的是:

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

這意味着(感謝劇組串),那要添加字符串你的陣列 - 和而不是SimpleXMLElement對象了。


作爲參考:手冊的相關章節:Type Casting

+0

謝謝 - 我已經發布了一個跟進的問題,如果你會這麼好心。我更加期待找出什麼時候我不投,我沒有得到一個字符串添加。 – barfoon 2011-04-14 19:27:21

0

在你的第一個例子,你應該:

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

你的第二個例子給出了一個字符串數組,因爲你正在轉換的SimpleXMLElements使用(string)投字符串。在你的第一個例子中,你不是,所以你得到一個SimpleXMLElements數組。

1

對不起,剛纔注意到上面有更好的答案,但正則表達式本身仍然有效。 您是否試圖在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); 
       } 

     } 
相關問題