2015-10-11 3 views
0

Здесь я хочу просто загрузить URL-адрес и отобразить все изображения с помощью PHP. Вот код, который я использовал, но я получаю сообщение об ошибке:PHP Получить элемент по тегам Ошибка

Ошибка:

Call to a member function getElementsByTagName() on string 

Как я могу получить этот код, чтобы распечатать изображения и или другие элементы, такие как H1 или P? Вот мой код:

Код:

<?php 

$to_crawl = "http://thechive.com/"; 

function get_links($url){ 
    $input = file_get_contents($url); 
    $images = $input->getElementsByTagName('img'); 
    echo $images; 
} 

get_links($to_crawl); 

?> 
+0

вы создали его как DOMDocument где-то еще? [php manual domDocument] (http://php.net/manual/en/class.domdocument.php) – Billy

+1

'getElementByTagNAme' - это метод класса DOMDocument – Mihai

+1

После создания объекта DOM вы можете использовать этот метод. Узнайте больше об этом в первую очередь. – CodeGodie

ответ

1
<?php 
/* Utility class to simplify getting dom object from html */ 
class htmldom{ 
    private $html; 
    public function __construct($data=false, $convert=true){ 
     try{ 
      if(!$data) return false; 
      libxml_use_internal_errors(true); 
      $this->html = new DOMDocument('1.0','utf-8'); 
      $this->html->validateOnParse=false; 
      $this->html->standalone=true; 
      $this->html->preserveWhiteSpace=true; 
      $this->html->strictErrorChecking=false; 
      $this->html->substituteEntities=false; 
      $this->html->recover=true; 
      $this->html->formatOutput=true; 

      $this->html->loadHTML($convert ? mb_convert_encoding($data, 'utf-8') : $data); 

      $parse_errs=serialize(libxml_get_last_error()); 
      libxml_clear_errors(); 

     }catch(Exception $e){ 
      die($e->getMessage());  
     } 
    } 
    public function gethtml(){ 
     return $this->html; 
    } 
} 



$url = "http://thechive.com/"; 
/* store results here */ 
$data=array(); 

/* The tags you are interested in finding within the html src */ 
$tags=array('img','p','h1'); 


/* Create the dom object with html from url */ 
$dom=new htmldom(file_get_contents($url), true); 
$html=$dom->gethtml(); 

/* Get all tags */ 
$col=$html->getElementsByTagName('*'); 

if($col->length > 0){ 
    foreach($col as $tag) { 
     /* Is this a tag we are interested in? */ 
     if(in_array($tag->tagName, $tags)){ 
      if($tag->tagName=='img') $data[]=$tag->getAttribute('src'); 
      else $data[]=array('tag' => $tag->tagName, 'value' => $tag->nodeValue); 
     } 
    } 
} 
$dom=$html=null; 
/* Do stuff with the results */ 
echo '<pre>',print_r($data,true),'</pre>'; 
?> 
+0

Ничего себе! Большое спасибо. Я понимаю, что происходит здесь вообще, но детали, которые я все еще хочу изучить. Не могли бы вы указать мне в правильном направлении для некоторых уроков для этого? или вы могли бы сделать как видео или Skype? Im действительно заинтересована в том, чтобы научиться писать так самостоятельно. –

+1

Удовольствие - рад, что это помогло! Я бы предложил прочитать заметки на PHP-сайте для 'DomDocument()' - http://php.net/manual/en/class.domdocument.php &/или руководства, которое поставляется с PHP. Попробуйте поэкспериментировать с приведенным выше кодом и в сочетании с другими фрагментами, найденными на сайте php ~, например, попробуйте получить другие атрибуты из элементов html '$ node-> getAttribute ('data-banana')' и т. Д. – RamRaider

1

попробовать это

<?php 
 

 
$to_crawl = "http://thechive.com/"; 
 

 

 
function get_links($to_crawl) { 
 

 
    // Create a new DOM Document to hold our webpage structure 
 
    $the_html = new DOMDocument(); 
 

 
    // Load the url's contents into the DOM 
 
    $the_html->loadHTMLFile($to_crawl); 
 

 
    // Empty array to hold all links to return 
 
    $links = array(); 
 

 
    //Loop through each <img> tag in the dom and add it to the link array 
 
    foreach($the_html->getElementsByTagName('img') as $link) { 
 
     $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue); 
 
    } 
 

 
    
 
    // echo links 
 
    foreach($links as $link){ 
 
     echo $link."<br>"; 
 

 
//Return the links 
 
    return $links; 
 

 
} 
 

 
get_links($to_crawl); 
 

 
?>

+0

Спасибо за быстрый ответ! Я получаю эту ошибку с вашим кодом: DOMDocument :: loadHTMLFile(): ID all-css-0, уже определенный в http://thechive.com/. что это значит? Знаете ли вы хорошие учебные пособия для dom? –

1

Вам нужно создать новый объект DomDocument() перед обращением к методу getElementsByTagName. Вот краткий пример:

<?php 
libxml_use_internal_errors(true); 

$html = file_get_contents("http://thechive.com/"); 
$dom = new DomDocument(); 
$dom->loadHtml($html); 
$images = $dom->getElementsByTagName('img'); 
foreach ($images as $image) { 
    echo $image->getAttribute('src'); 
} 
0
<?php 

# Use the Curl extension to query Google and get back a page of results 
$html = file_get_contents("http://thechive.com/"); 


# Create a DOM parser object 
$dom = new DOMDocument(); 

# Parse the HTML from Google. 
# The @ before the method call suppresses any warnings that 
# loadHTML might throw because of invalid HTML in the page. 
@$dom->loadHTML($html); 

# Iterate over all the <img> tags 
foreach($dom->getElementsByTagName('img') as $link) { 
     # Show the <a href> 
     echo $link->getAttribute('src'); 
     echo "<br />"; 
} 
?> 
Смежные вопросы