简体   繁体   中英

PHP to include specific part of file

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

    $article1 = file_get_contents("article1.php");

    echo substr(strip_tags($article1), 0, 100) . "...";

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM