我使用simple_html_dom
網絡報廢應用程序的工作。我需要提取網頁中的所有圖像。以下是可能:PHP致命錯誤:無法使用類型simple_html_dom的對象數組
<img>
標籤圖像- 如果在同一頁面中
<style>
標籤的CSS。 - 如果與
<div>
或與其他標籤內嵌樣式的圖像。
我可以通過使用下面的代碼颳去所有圖像。
function download_images($html, $page_url , $local_url){
foreach($html->find('img') as $element) {
$img_url = $element->src;
$img_url = rel2abs($img_url, $page_url);
$parts = parse_url($img_url);
$img_path= $parts['path'];
$url_to_be_change = $GLOBALS['website_server_root'].$img_path;
download_file($img_url, $GLOBALS['website_local_root'].$img_path);
$element->src=$url_to_be_change;
}
$css_inline = $html->find("style");
$matches = array();
preg_match_all("/url\((.*?)\)/", $css_inline, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$img_url = trim($match[1], "\"'");
$img_url = rel2abs($img_url, $page_url);
$parts = parse_url($img_url);
$img_path= $parts['path'];
$url_to_be_change = $GLOBALS['website_server_root'].$img_path ;
download_file($img_url , $GLOBALS['website_local_root'].$img_path);
$html = str_replace($img_url , $url_to_be_change , $html);
}
return $html;
}
$html = download_images($html , $page_url , $dir); // working fine
$html = str_get_html ($html);
$html->save($dir. "/" . $ff);
請注意,我在下載圖片後也修改了HTML。
下載工作正常。但是,當我試圖保存HTML,那麼它給了以下錯誤:
PHP Fatal error: Cannot use object of type simple_html_dom as array
重要:其工作完全正常,如果我不使用str_replace
和第二循環。
Fatal error: Cannot use object of type simple_html_dom as array in /var/www/html/app/framework/cache/includes/simple_html_dom.php on line 1167
的$ HTML作爲最後一個參數在你的str_replace調用中是一個對象,而不是一個數組。 str_replace顯然不喜歡那樣。您需要找出另一種將數據表示爲數組的方法,或者以某種方式重新處理它。 –
obligatory http://stackoverflow.com/a/1732454/3044080 – nomistic