1

I'm making a website and I would like to have a news/blog type section, each post will be very similar in stile to others (one image + text). I'm currently storing text of posts in a JSON files. I think it would be a waste to create a separate page for every post since I just need to retrieve the json and put text into correct places on the page. How can I do it so that as few repeated pages are used as possible? I'm currently using js and php.

Lets say I have a main page with sidebar saying something like:

  1. Post 1
  2. Post 2
  3. ...
  4. Post n

What should I do, so that when I click on any of the posts a new page opens with the correct post, bearing in mind that I don't want to have a different page for each post.

Rizhiy
  • 775
  • 1
  • 9
  • 31
  • You could probably just use PHP to read the JSON files and parse the contents into HTML to appear on the pages. Use query variables (or .htaccess URL rewriting if you want semantic URLs) to determine what file to grab and serve. – Hydrothermal Feb 20 '16 at 23:51
  • I understand that, but that way I still need a separate page to send the correct get request. – Rizhiy Feb 20 '16 at 23:54

1 Answers1

1

Assuming that your JSON text post looks like this:

{
    "contents": "my file contents"
}

The following code should work:

<p>Some consistent header.</p>
<p>
    Requested file contents:
    <?php
    if(isset($_GET["file"])) {
        $requested_file = $_GET["file"];
        $file = json_decode(file_get_contents("json/$requested_file.json"), true);
        echo $file["contents"];
    } else {
        // Some kind of error
    }
    ?>
</p>
<p>Some consistent footer.</p>

This checks for a file query variable in the URL (e.g. ?file=post1) and requests the corresponding JSON file by using the relative path json/[file].json. It reads the contents key and puts its value on the screen. Using this one PHP file, you can request any JSON file and have its contents returned.

Hydrothermal
  • 4,851
  • 7
  • 26
  • 45
  • Ok, but how can I display different files with a single page? – Rizhiy Feb 21 '16 at 00:09
  • If your page is "view_post.php" and your JSON files are named "post1.json", "post2.json", and so on, request "view_post.php?file=post1", "view_post.php?file=post2", etc. – Hydrothermal Feb 21 '16 at 00:10
  • Ok, so the part after the question mark in the url acts as a selector? – Rizhiy Feb 21 '16 at 00:14
  • Correct. If you'd prefer to have a path like "view_post/post1", check [this SO answer](http://stackoverflow.com/a/13003447/2789699) about .htaccess URL rewriting. – Hydrothermal Feb 21 '16 at 01:45