以前,我使用php将表单数据附加到json文件中。目前我正在使用php文件而不是json文件,它有两个参数,如图所示,它显示给用户。
Image url link

我的表格是



<form action="process.php" method="POST">
	Name:<br>
	<input type="text" name="name">
	<br><br/>
	Download Url:<br>
	<input type="text" name="downloadUrl">
	<br><br>




	<input type="submit" value="Submit">
</form>





我的PHP文件是



{"downloadurl":[


{"name":"भाद्र ६ : LCR Series",
"downloadurl":"https://drive.google.com/uc?export=download&id=1In76AN2Y5_qXV5ucXDXWx1PTKTTIvD3d"

},

{"name":"भाद्र ६ : LCR Parallel",
"downloadurl":"https://drive.google.com/uc?export=download&id=1R9Ia4X12JZMsTn_vF6z443K6wKI2Rfeu"

}


]}





我如何使用附加新数据,以便在单击“提交”按钮时将新数据添加到上述php文件的顶部,以便将新文件



    {"downloadurl":[


 {"name":"भाद्र ६ : New appended Data",
    "downloadurl":"This is new Text added on Top"

    },



    {"name":"भाद्र ६ : LCR Series",
    "downloadurl":"https://drive.google.com/uc?export=download&id=1In76AN2Y5_qXV5ucXDXWx1PTKTTIvD3d"

    },

    {"name":"भाद्र ६ : LCR Parallel",
    "downloadurl":"https://drive.google.com/uc?export=download&id=1R9Ia4X12JZMsTn_vF6z443K6wKI2Rfeu"

    }


    ]}





在顶部,以便将其显示给用户

最佳答案

从您的问题来看,我认为这将解决您的问题。我正在使用array_unshift(),因为您对短语on top的使用使我认为您想在现有数据之前显示数据,如果这样做不正确,请用array_unshift()替换array_push()在数据之后添加,或参见解决方案2。

解决方案1:

<?php

    //This is where your JSON file is located
    $jsonFile = '/path/to/json/file';

    //Get the contents of your JSON file, and make it a useable array.
    $JSONString = json_decode( file_get_contents( $jsonFile ), true );

    //This is the new data that you want to add to your JSON
    $newData = array(
            //Your data goes here
        );

    //Add the new data to the start of your JSON
    array_unshift($existingData, $newData);

    //Encode the new array back to JSON
    $newData = json_encode( $existingData, JSON_PRETTY_PRINT );

    //Put the JSON back into the file
    file_put_contents($jsonFile, $newData);

?>


解决方案2:

<?php

    //This is where your JSON file is located
    $jsonFile = '/path/to/json/file';

    //This is the new data that you want to add to your JSON
    $newData = array(
            //Your data goes here
        );

    //Encode the new data as JSON
    $newData = json_encode( $newData, JSON_PRETTY_PRINT );

    //append the new data to the existing data
    file_put_contents( $jsonFile, $newData, FILE_APPEND );

?>

08-19 15:38
查看更多