📜  如何使用PHP从 html 中提取 img src 和 alt?

📅  最后修改于: 2022-05-13 01:54:11.663000             🧑  作者: Mango

如何使用PHP从 html 中提取 img src 和 alt?

使用PHP从 HTML 页面中提取图像属性,如 'src'、'alt'、'height'、'width' 等。可以使用以下步骤完成此任务。

  • 在变量(DOM 变量)中加载 HTML 内容。
  • 选择该文档中的每个图像。
  • 选择属性并将其内容保存到变量中。
  • 根据需要输出为 HTML img 对象或普通值。

示例 1:本示例将图像对象显示为输出。

loadHTMLFile($url);
      
    // Selecting all image i.e. img tag object
    $anchors = $dom -> getElementsByTagName('img');
      
    // Extracting attribute from each object
    foreach ($anchors as $element) {
          
        // Extracting value of src attribute of
        // the current image object
        $src = $element -> getAttribute('src');
          
        // Extracting value of alt attribute of
        // the current image object
        $alt = $element -> getAttribute('alt');
          
        // Extracting value of height attribute
        // of the current image object
        $height = $element -> getAttribute('height');
          
        // Extracting value of width attribute of
        // the current image object
        $width = $element -> getAttribute('width');
          
        // Given Output as image with extracted attribute,
        // you can print value of those attributes also
        echo ''.$alt.'';
    }
} 
   
crawl_page("https://www.google.com/search?q=geeksforgeeks&tbm=isch");
   
?>

输出:

示例 2:此示例显示图像对象的属性。

loadHTMLFile($url);
      
    // Selecting all image i.e. img tag object
    $anchors = $dom -> getElementsByTagName('img');
      
    // Extracting attribute from each object
    foreach ($anchors as $element) {
          
        // Extracting value of src attribute of
        // the current image object
        $src = $element -> getAttribute('src');
          
        // Extracting value of alt attribute of
        // the current image object
        $alt = $element -> getAttribute('alt');
          
        // Extracting value of height attribute
        // of the current image object
        $height = $element -> getAttribute('height');
          
        // Extracting value of width attribute of
        // the current image object
        $width = $element -> getAttribute('width');
          
        // Display Output as value of those attributes
        echo 'src='.$src.'
alt='.$alt.'
height='                 . $height.'
width='.$width.'
';     } }      crawl_page("https://www.google.com/search?q=flowers&tbm=isch");     ?>

输出: