Example of Capturing Novel Website Content Function Implemented by PHP

  • 2021-12-12 04:06:21
  • OfStack

In this paper, an example is given to describe the function of crawling novel website content realized by PHP. Share it for your reference, as follows:

Crawl free content, get mobile phones, listen to books, and do it properly.


ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; GreenBrowser)');
ini_set('max_execution_time', '0');
$base = 'https://www.qu.la/book/19434/';
$start = '7504808.html';
$content_grep = '/&nbsp;&nbsp;&nbsp;&nbsp;(.*)<br\/>/';
//$content_grep = '/<div id="content">(.*)<br\/>/sS';
$next_grep = '/<a id="pager_next" href=\"(\d+\.html)\" target="_top" class="next"> Under 1 Chapter <\/a>/';
$next = $start;
$file_name = ' Listen to the book .txt';
while($next) {
  echo 'getting ' . $next . PHP_EOL;
  $result = file_get_contents($base . $next);
  preg_match_all($content_grep, $result, $match);
  $isTitle = true;
  $content = "";
  foreach($match[1] as $line) {
    $line  = str_replace("<br/>", '', $line);
    $line  = str_replace(" ", '', $line);
    if($isTitle) {
      $content = $line . PHP_EOL . PHP_EOL;
      $isTitle = false;
    } else {
      $content .= '    ' . $line . PHP_EOL . PHP_EOL;
    }
  }
  $file = fopen($file_name, 'a');
  echo 'write length: ' . strlen($content) . PHP_EOL;
  fwrite($file, $content);
  fclose($file);
  echo '.';
  preg_match($next_grep, $result, $match);
  $next = $match[1];
}

For more readers interested in PHP related content, please check the topics on this site: "php socket Usage Summary", "php String (string) Usage Summary", "PHP Mathematical Operation Skills Summary", "php Object-Oriented Programming Introduction Tutorial", "PHP Array (Array) Operation Skills Complete Book", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Network Programming Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: