2016-09-04 13 views
1

OK,所以我有有有,我正在尋找刮,並返回以下信息,其圖像的網頁:返回各自DIV具有一定的類名在PHP

  • 基地圖片網址( 「website.com/imagepage」)
  • 圖片URL( 「website.com/image.png」),如果它有一個( 「哇,好形象」
  • 圖片報價)

我有努力返回一個圖像,但我需要它返回所有這些(大約有5)

這是我的時刻:

function getMostRecentScreenshot($url) { 
$content = file_get_contents($url); 

$first_step = explode('<div class="imageWall5Floaters">' , $content); 
$second_step = explode('<div style="clear: left;"></div>' , $first_step[1]); 

return $second_step[0]; 
} 

這是它返回

<div class="floatHelp"> 
<a href="websiteurl.com/imagepage" onclick="return OnScreenshotClicked(9384938);" class="profile_media_item modalContentLink " data-desired-aspect="1.77777777778"> 
    <div style="background-image: url('website.com/image');" class="imgWallItem " id="imgWallItem_757249198"> 
     <div style="position: relative;"> 
      <input type="checkbox" style="position: absolute; display: none;" name="screenshots[9384938]" class="screenshot_checkbox" id="screenshot_checkbox_9384938" /> 
     </div> 
     <div class="imgWallHover" id="imgWallHover9384938"> 
      <div class="imgWallHoverBottom"> 
       <div class="imgWallHoverDescription "> 
        <q class="ellipsis">Quote about the image</q> 
       </div> 
      </div> 
     </div> 


    </div> 
</a> 

該給圖像有不同的ID(在9384938部分)。

我將如何從它返回的信息中獲得所需的信息?

我在返回的數據圖像(種)之一的時候,又有功能,但它基本上只是用的爆炸,這是非常混亂的代碼完全一樣的事情。

+4

你會發現它很有用:http://simplehtmldom.sourceforge.net/ –

+0

我完全忘了這simplehtmldom存在。謝謝@KostasMitsarakis! –

+0

你需要使用正則表達式來拉你想要的。 –

回答

0

你可以使用PHP的DOMDocument類使用此項功能:

function getDataFromHTML($html) { 
    $doc = new DOMDocument(); 
    $html = $doc->loadHTML($html); 

    foreach($doc->getElementsByTagName('a') as $a) { 
     if (strpos($a->getAttribute('class'), 'profile_media_item') !== false) { 
      $row = []; 
      $row['baseURL'] = $a->getAttribute('href'); 
      foreach($a->getElementsByTagName('div') as $div) { 
       preg_match("~(?<=url\(['\"]).*?(?=['\"])~", 
          $div->getAttribute('style'), $attr); 
       $row['imageURL'] = reset($attr); 
       foreach($a->getElementsByTagName('q') as $q) { 
        $row['quote'] = $q->textContent; 
        break; 
       } 
       break; 
      } 
      $result[] = $row; 
     } 
    } 
    return $result; 
} 

稱其爲:

$result = getDataFromHTML($html); 

輸出的樣本數據是:

array (
    array (
    'baseURL' => 'websiteurl.com/imagepage', 
    'imageURL' => 'website.com/image', 
    'quote' => 'Quote about the image' 
) 
) 

外陣列將如果在具有多個DOM結構的HTML字符串上運行,則會有更多這樣的條目秒。

+0

這工作完美,謝謝!只有問題,是不是返回imageURL?在編輯之前,它將所有內容都返回給所有人,但編輯現在可以返回所有內容,減去圖像? –

+1

更正:我意外刪除了第二個'break' – trincot

+0

完美地工作,非常感謝! :d –

相關問題