Get HREF Atribute of anchor tag by class name in PHP

I was looking for extracting href value from html link(a) tags in PHP. Came up with the following solution. It’s useful to extract links from a website


function get_href_attribute("Google","a","my_tag")

function get_href_attribute($html,$tag,$class)
{

   // Load the HTML in DOM
   $doc = new DOMDocument();
   $doc->loadHTML($html);

   // Then select all anchor tags
   $all_anchor_tags = $doc->getElementsByTagName($tag);
   $href_array = array();
   foreach ($all_anchor_tags as $_tag) {
      if ($_tag->getAttribute("class") == $class) {
         // If match class get the href value
         $href_array[] = $link->getAttribute("href");
      }
   }
  return $href_array;
}

Leave a Reply

Your email address will not be published. Required fields are marked *