如何在PHP中向JSON文件添加数组值?PHP新手求助
Hey there! Let's walk through how to get this working properly—since you're new to PHP, I'll break it down step by step. The big thing to remember here is: frontend JavaScript can't directly write files on your server. You need a PHP backend script to handle saving the data permanently.
First, your current Checker variable is a JavaScript object, not a pure JSON file. Let's create a proper JSON file (name it data.json) with valid JSON syntax:
[ { "name": "Google", "url": "google.es" }, { "name": "Yahoo", "url": "yahoo.com" } ]
Note: I removed the var Checker = prefix and the trailing comma after the last object (JSON doesn't allow trailing commas).
Modify your SSL.Add() function in script.js to send the form data to a PHP script using the Fetch API. This will let us pass the input values to the backend for saving:
function Add() { // Grab input values and trim whitespace const name = document.getElementById('add-name').value.trim(); const url = document.getElementById('add-link').value.trim(); // Basic validation if (!name || !url) { alert('Please fill in both Name and Link fields!'); return; } // Send data to PHP script fetch('save-data.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, url }) }) .then(response => response.json()) .then(result => { if (result.success) { alert('Site added successfully!'); // Refresh the site list using your existing start() function start(); // Clear the form document.getElementById('add-name').value = ''; document.getElementById('add-link').value = ''; } else { alert(`Oops: ${result.message}`); } }) .catch(error => { console.error('Error:', error); alert('Something went wrong—please try again.'); }); }
Make sure your form's onsubmit attribute points to this function (adjust SSL.Add() to just Add() if needed).
Now make a new file called save-data.php. This script will handle receiving the data, validating it, updating the JSON file, and sending a response back to the frontend:
<?php // Set response type to JSON header('Content-Type: application/json'); // Only accept POST requests if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode([ 'success' => false, 'message' => 'Invalid request method.' ]); exit; } // Read and parse the incoming JSON data $input = file_get_contents('php://input'); $submittedData = json_decode($input, true); // Validate required fields if (!isset($submittedData['name'], $submittedData['url']) || trim($submittedData['name']) === '' || trim($submittedData['url']) === '') { echo json_encode([ 'success' => false, 'message' => 'Name and URL are required.' ]); exit; } // Path to our JSON file $jsonFilePath = 'data.json'; // Create file if it doesn't exist if (!file_exists($jsonFilePath)) { file_put_contents($jsonFilePath, '[]'); } // Read existing data $existingJson = file_get_contents($jsonFilePath); $sites = json_decode($existingJson, true); // Check if JSON parsing worked if (json_last_error() !== JSON_ERROR_NONE) { echo json_encode([ 'success' => false, 'message' => 'Error reading existing site data.' ]); exit; } // Add the new site to the array $sites[] = [ 'name' => trim($submittedData['name']), 'url' => trim($submittedData['url']) ]; // Write updated data back to the file $updatedJson = json_encode($sites, JSON_PRETTY_PRINT); if (file_put_contents($jsonFilePath, $updatedJson) === false) { echo json_encode([ 'success' => false, 'message' => 'Could not save data. Check file permissions on your server.' ]); exit; } // Send success response echo json_encode([ 'success' => true, 'message' => 'Site added!' ]); ?>
Finally, modify your start() function to load data from the new data.json file instead of the old JS variable. Remove the <script src="js/json.json"></script> line from your HTML, then update script.js:
function start() { fetch('data.json') .then(response => response.json()) .then(sites => { const tableBody = document.getElementById('urls'); tableBody.innerHTML = ''; // Render each site in the table sites.forEach(site => { const row = document.createElement('tr'); row.innerHTML = `<td>${site.name} - ${site.url}</td>`; tableBody.appendChild(row); }); // Update counter document.getElementById('counter').textContent = `Total sites: ${sites.length}`; }) .catch(error => console.error('Failed to load sites:', error)); }
Important Notes
- File Permissions: Ensure your server has write access to
data.jsonand its parent directory. On most servers, setting permissions to644or664works. - Extra Validation: For better security, add URL validation using PHP's
filter_var($submittedData['url'], FILTER_VALIDATE_URL)to check if the input is a valid URL. - Error Handling: The example has basic error handling, but you can expand it to handle edge cases like duplicate entries if needed.
内容的提问来源于stack exchange,提问作者Joanmi

