Bruce Bruce - 1 month ago 5
HTML Question

PHP: Test for string of text inside html tags from file_get_contents string

I need to perform a series of tests on a url. The first test is a word count, I have that working perfectly and the code is below:

if (isset($_GET[article_url])){
$title = 'This is an example title';
$str = @file_get_contents($_GET[article_url]);
$test1 = str_word_count(strip_tags(strtolower($str)));
if($test1 === FALSE) { $test = '0'; }
if ($test1 > '550') {
echo '<div><i class="fa fa-check-square-o" style="color:green"></i> This article has '.$test1.' words.';
} else {
echo '<div><i class="fa fa-times-circle-o" style="color:red"></i> This article has '.$test1.' words. You are required to have a minimum of 500 words.';
}
}


Next I need to get all h1 and h2 tags from $str and test them to see if any contain the text $title and echo yes if so and no if not. I am not really sure how to go about doing this.

I am looking for a pure php means of doing this without installing php libraries or third party functions.

Answer

please try below code.

if (isset($_GET[article_url])){
    $title = 'This is an example title';
    $str = @file_get_contents($_GET[article_url]);

    $document = new DOMDocument();
    $document->loadHTML($str);

    $tags = array ('h1', 'h2');
    $texts = array ();
    foreach($tags as $tag)
    {
      //Fetch all the tags with text from the dom matched with passed tags
      $elementList = $document->getElementsByTagName($tag);
      foreach($elementList as $element)
      {
         //Store text in array from dom for tags
         $texts[] = strtolower($element->textContent);
      }
    }
    //Check passed title is inside texts array or not using php
    if(in_array(strtolower($title),$texts)){
        echo "yes";
    }else{
        echo "no";
    }
}