PHP CRUD JSON ficheiro em vez de uma base de dados como o mysql

eu estou em um pouco de pickle, eu recebi um pedido para criar aplicativo CRUD para editar o objeto JSON em um array e carregá-los. Fiz um pouco de pesquisa e deparei-me com ... http://www.taffydb.com mas não corresponde às minhas exigências.

editar: eu também encontrei jtables, mas ele usa mysql, semelhante a http://www.jeasyui.com/tutorial/app/crud.php mas também usa o mysql. É possível saltar a parte da base de dados e escrever directamente para o ficheiro JSON?

Como este é um arquivo JSON muito pequeno, ter uma base de dados parece excessivo. Tenho vários objectos na matriz JSON, dos quais um aplicativo externo leria.

Quais são as opções viáveis que posso escolher? Idealmente, o aplicativo precisa Adicionar/Editar/Excluir do conteúdo do navegador para o arquivo JSON.

actualmente sou capaz de mostrar os dados de acordo com as tabelas. O meu código parece isto:

PHP:

<?php
$getfile = file_get_contents('test.json');
$jsonfile = json_decode($getfile);
?>

HTML:

<table align="center">
<tr>
  <th>Title</th>
  <th>Background Image</th>
  <th>Video URL (Link to Video)</th>
  <th>Description of Video</th>
</tr>
  <?php
    foreach ($jsonfile->playlist as $obj) {
      echo '<tr><td>' . $obj->title . '</td>';
      echo '<td>' . $obj->title_bg . '</td>';
      echo '<td>' . $obj->link . '</td>';
      echo '<td>' . $obj->description . '</td></tr>';
    }
  ?>
</table>

JSON:

{
  "playlist": [
    {
      "title": "Test title",
      "title_bg": "link/to/image.png",
      "link": "https://www.google.com",
      "description": "This is a test JSON Object"
    }
  ]
}

o ficheiro JSON terá vários objectos na matriz playlist

Author: fupuchu, 2016-07-11

1 answers

Podes fazê - lo desta maneira.

Teste.json

{
    "playlist": [
        {
            "title": "Test title1222212321321321",
            "title_bg": "link\/to\/image.png",
            "link": "https:\/\/www.google.com",
            "description": "This is a test JSON Object"
        }, {
            "title": "sdfdasf",
            "title_bg": "adsfdas",
            "link": "fdasf",
            "description": "dasfdasf"
        }, {
            "title": "This is a title ",
            "title_bg": "This is a title bg",
            "link": "This is a link2",
            "description": "This is a description"
        }
    ]
}

Índice.php

<?php
$getfile = file_get_contents('test.json');
$jsonfile = json_decode($getfile);
?>
<a href="http://localhost/test/add.php">Add</a>
<table align="center">
    <tr>
        <th>Title</th>
        <th>Background Image</th>
        <th>Video URL (Link to Video)</th>
        <th>Description of Video</th>
        <th></th>
    </tr>
    <tbody>
        <?php foreach ($jsonfile->playlist as $index => $obj): ?>
            <tr>
                <td><?php echo $obj->title; ?></td>
                <td><?php echo $obj->title_bg; ?></td>
                <td><?php echo $obj->link; ?></td>
                <td><?php echo $obj->description; ?></td>
                <td>
                    <a href="http://localhost/test/edit.php?id=<?php echo $index; ?>">Edit</a>
                    <a href="http://localhost/test/delete.php?id=<?php echo $index; ?>">Delete</a>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

Edite.php

<?php
if (isset($_GET["id"])) {
    $id = (int) $_GET["id"];
    $getfile = file_get_contents('test.json');
    $jsonfile = json_decode($getfile, true);
    $jsonfile = $jsonfile["playlist"];
    $jsonfile = $jsonfile[$id];
}

if (isset($_POST["id"])) {
    $id = (int) $_POST["id"];
    $getfile = file_get_contents('test.json');
    $all = json_decode($getfile, true);
    $jsonfile = $all["playlist"];
    $jsonfile = $jsonfile[$id];

    $post["title"] = isset($_POST["title"]) ? $_POST["title"] : "";
    $post["title_bg"] = isset($_POST["title_bg"]) ? $_POST["title_bg"] : "";
    $post["link"] = isset($_POST["link"]) ? $_POST["link"] : "";
    $post["description"] = isset($_POST["description"]) ? $_POST["description"] : "";



    if ($jsonfile) {
        unset($all["playlist"][$id]);
        $all["playlist"][$id] = $post;
        $all["playlist"] = array_values($all["playlist"]);
        file_put_contents("test.json", json_encode($all));
    }
    header("Location: http://localhost/test/index.php");
}
?>
<?php if (isset($_GET["id"])): ?>
    <form action="http://localhost/test/edit.php" method="POST">
        <input type="hidden" value="<?php echo $id ?>" name="id"/>
        <input type="text" value="<?php echo $jsonfile["title"] ?>" name="title"/>
        <input type="text" value="<?php echo $jsonfile["title_bg"] ?>" name="title_bg"/>
        <input type="text" value="<?php echo $jsonfile["link"] ?>" name="link"/>
        <input type="text" value="<?php echo $jsonfile["description"] ?>" name="description"/>
        <input type="submit"/>
    </form>
<?php endif; ?>

Apagar.php

<?php

if (isset($_GET["id"])) {
    $id = (int) $_GET["id"];
    $all = file_get_contents('test.json');
    $all = json_decode($all, true);
    $jsonfile = $all["playlist"];
    $jsonfile = $jsonfile[$id];

    if ($jsonfile) {
        unset($all["playlist"][$id]);
        $all["playlist"] = array_values($all["playlist"]);
        file_put_contents("test.json", json_encode($all));
    }
    header("Location: http://localhost/test/index.php");
}

Add.php

<form action="http://localhost/test/add.php" method="POST">
    <input type="text" name="title" placeholder="title"/>
    <input type="text" name="title_bg" placeholder="title_bg"/>
    <input type="text" name="link" placeholder="link"/>
    <input type="text" name="description" placeholder="description"/>
    <input type="submit" name="add"/>
</form>
<?php
if (isset($_POST["add"])) {
    $file = file_get_contents('test.json');
    $data = json_decode($file, true);
    unset($_POST["add"]);
    $data["playlist"] = array_values($data["playlist"]);
    array_push($data["playlist"], $_POST);
    file_put_contents("test.json", json_encode($data));
    header("Location: http://localhost/test/index.php");
}
?>

Para executar o programa, deverá indicar em cada um destes ficheiros um local de ficheiros JSON. Você também tem que mudar o endereço dos links para o seu ambiente.

 8
Author: rad11, 2016-07-11 10:00:09