如何在php文件中附加数据

时间:2018-09-28 14:44:07

标签: javascript php json

以前,我使用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"

    }


    ]}

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

2 个答案:

答案 0 :(得分:1)

我不明白为什么要在PHP文件的末尾附加文本,但是可以将file_put_contents()FILE_APPEND标志一起使用。

答案 1 :(得分:0)

从您的问题来看,我认为这将解决您的问题。我使用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 );

?>