PHP包含文件的特定部分 [英] PHP to include specific part of file

查看:89
本文介绍了PHP包含文件的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主页index.php。我有两篇文章,例如:article1.php和article2.php。



在我的主页上,我想展示两篇文章的预览。但由于这些文章太长,我只想显示5行文章(或100个字符或其他解决方案)。在文章的这些第一行之后,它将以...结尾,并且这些行链接到实际的文章页面; article1.php或article2.php



这应该是一个非常简单的事情,我猜想,显示了一部分我用代码include导入的文本。顺便说一句,我不包括一个文本文件。这是article1.php,因此代码必须忽略其他所有内容,如标题,照片与必须只关注文本的第一行。



有什么建议?

如果您的 article1.php 文件包含整个页面,包括HTML标题和(显然)一些PHP代码,这实际上不是一个理想的起点。您应该将文章(只是原始文章文本)存储在单独的文件中。然后在不同的地方重复使用它的不同部分很简单:



article1.txt

 < p> Lorem ipsum。< / p> 
< p> Foobar baz。< / p>

article1.php

 < html> 
< head>
...
< / head>
< body>
...
<?php include'article1.txt'; ?>
...
< / body>

index.php

 < html> 
< head>
...
< / head>
< body>
...
<?php
$ article1 = file_get_contents('article1.txt');
echo substr(strip_tags($ article1),0,100)。 ...;
?>
< a href =article1.php>了解更多< / a>
...
< / body>

通过这种方式,您甚至可以自动生成 index.php 通过自动浏览文章目录中的所有 .txt 文件并输出这些链接。将文章存储在数据库中会使其更加灵活。继续沿着这些路线,你几乎重新发明了一个CMS,所以你可能要考虑使用Wordpress或者像它这样的系统。


I have a homepage index.php. And I have two articles for example: article1.php and article2.php.

On my homepage I want to show previews of my two articles. But since these articles are too long, I only want to show 5 lines of an article (or 100 characters or another solution). After these first lines of the article it will end with "..." and these lines are linked to the actual article page; article1.php or article2.php

It should be a really simple thing I guess, showing some part of the text which I'm importing with the code "include". By the way I'm not including a text file. It's article1.php, so the code must ignore everything else like headers, photos vs. Must focus only the first lines of the text.

Any advice?

解决方案

If your article1.php file contains a whole page including HTML header and (apparently) some PHP code, this is really not an ideal starting point. You should store your articles (just the raw article text) in separate files. It's then simple to reuse different parts of it in different places:

article1.txt

<p>Lorem ipsum.</p>
<p>Foobar baz.</p>

article1.php

<html>
<head>
    ...
</head>
<body>
   ...
   <?php include 'article1.txt'; ?>
   ...
</body>

index.php

<html>
<head>
    ...
</head>
<body>
   ...
   <?php
       $article1 = file_get_contents('article1.txt');
       echo substr(strip_tags($article1), 0, 100) . '...';
  ?>
  <a href="article1.php">Read more</a>
   ...
</body>

This way you can even automate the generation of links on your index.php by automatically going through all .txt files in the article directory and outputting those links. Storing articles in a database would make this even more flexible. Continuing along those lines you're pretty much reinventing a CMS though, so you might want to consider using Wordpress or some system like it.

这篇关于PHP包含文件的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆