分享自用的php爬取网页,读取、写入txt语句


emmm,今天来分享自己常用的php语句,关于txt文本的读取和写入!
老鸟直接飞过
首先来发读取的代码

1 $file_path = "content.txt";
2 //判断是否有这个文件
3 if(file_exists($file_path)){
4 $fp = fopen($file_path,"r");
5 $str = fread($fp,filesize($file_path));//指定读取大小,这里把整个文件内容读取出来
6 //关闭文件读取
7 fclose($fp);
8 }
9 然后我们就可以操作内容了,$str为我们的txt文本内容

我们可以进行操作,比如分割什么,也就是读取后想做什么事,我就举个例子
content.txt 里面放

https://www.dchuanbao.com/x/lol%E5%B2%A9%E9%9B%80%E5%A4%A7%E6%8B%9B

奥特曼格斗进化3

然后,我想我读取每个网页的标题,应该怎么办呢?
第一步首先要分割!
那么就是

//以换行符 来分割
$gourl=explode("\n",$str);

  然后就会生成一个分割后的数组,那么就需要循环遍历了!

foreach ($gourl as &$go) {
$html=file_get_contents($go);
preg_match('/(.*?)<\/title>/',$html,$title1);
print_r($title1));
}
</pre>

<p>  ok!爬取标题就大功告成了!,然后就是写入到txt</p>

<pre class="brush:php;gutter:true;">file_put_contents('title.txt', $title1[1].PHP_EOL,  FILE_APPEND);
</pre>

<p>解释一下上面的写入语句,把爬取到的标题内容写入到title.txt文本,自动换行、追加<br>好了,今天分享到这里。</p>
<p>转载地址:分享自用的php爬取网页,读取、写入txt语句</p>
						  
					  </div>
						<!--conend-->
							<div class="p-2"></div>

						<div class="arcinfo my-3 fs-7 text-center">
							
							
										
						



						</div>
						
						<div class="p-2"></div>

						

						
					</div>
					<div class="p-2"></div>
					<!--xg-->
					<div class="lbox p-4 shadow-sm rounded-3">
						<div class="boxtitle"><h2 class="fs-4">相关</h2></div>
						
<hr>				
						
			            
            
            <!---->
                                    
           <!---->
  			
						

					</div>
					<!--xgend-->
				</div>

				<div class="col-lg-3 col-12 p-0 ps-lg-2">
					<!--box-->									
					<!--boxend-->
					<!--<div class="p-2"></div>-->

					<!--box-->
									<div class="lbox p-4 shadow-sm rounded-3">
					
									   <div class="boxtitle pb-2"><h2 class="fs-4"><a href="#">标签</a></h2></div>
										<div class="clearfix"></div>
										<ul class="m-0 p-0 fs-7 r-tag">
										</ul>
									

										
										<div class="clearfix"></div>
									</div>
					<!--box end-->

					
				</div>

			</div>
		
		
		
		</div>	

</main>
						<div class="p-2"></div>
<footer>
<div class="container-fluid p-0 bg-black">
	<div class="container p-0  fs-8">
	<p class="text-center m-0 py-2 text-white-50">一品网 <a class="text-white-50" href="https://beian.miit.gov.cn/" target="_blank">冀ICP备14022925号-6</a></p>
	</div>	
</div>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6e3dd49b5f14d985cc4c6bdb9248f52b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
</footer>
		
<script src="/skin/bootstrap.bundle.js"></script>

</body>
</html>