PHP:无基础实现iOS应用通过POST向JSON文件添加数据
Hey there! Since you're new to PHP and trying to send level completion data from your iOS app to a JSON file via POST, let's get your code sorted out—your current approach writes plain text instead of valid JSON, which will cause headaches later when you try to read the data.
What's wrong with your original code?
Your current script appends lines like variable:value to the file, which isn't structured JSON. When you try to parse this file later (for stats, leaderboards, etc.), it'll throw errors because it doesn't follow JSON's strict format rules.
Corrected PHP Code (Produces Valid JSON)
This version will safely read existing data, add your new entry, and write everything back as properly formatted JSON:
<?php // Define the path to your JSON file $jsonFilePath = 'data.json'; // Initialize an empty array to hold all game data $gameRecords = []; // If the JSON file exists and isn't empty, load and parse it if (file_exists($jsonFilePath) && filesize($jsonFilePath) > 0) { $existingJson = file_get_contents($jsonFilePath); $gameRecords = json_decode($existingJson, true); // Reset the array if JSON parsing fails (prevents corrupted data) if (json_last_error() !== JSON_ERROR_NONE) { $gameRecords = []; } } // Extract your 3 POST variables (replace with your actual variable names!) // Using the null coalescing operator (`??`) to avoid errors if a variable is missing $newLevelRecord = [ 'completed_level' => $_POST['completed_level'] ?? '', 'user_score' => $_POST['user_score'] ?? '', 'player_id' => $_POST['player_id'] ?? '' ]; // Add the new record to our array of game data $gameRecords[] = $newLevelRecord; // Convert the array to formatted JSON (easy to read and parse) $updatedJson = json_encode($gameRecords, JSON_PRETTY_PRINT); // Write the updated JSON back to the file file_put_contents($jsonFilePath, $updatedJson); // Redirect to a success page (replace with your desired URL) header('Location: /success.html'); exit; ?>
Key Details to Note:
- Preserving Existing Data: We first load any existing JSON from the file so we don't overwrite old level completions—we just add new entries to the array.
- Valid JSON Output:
json_encodeensures the output follows strict JSON standards, so any tool (including your iOS app later) can parse it without issues. - Error Prevention: The
??operator handles cases where a POST variable might be missing, and we check for JSON parsing errors to avoid corrupted data. - File Permissions: Make sure your server has write access to
data.json—usually setting permissions to755works, but you might need777depending on your hosting setup.
Quick iOS Tip
When sending the POST request from your iOS app:
- If you're sending form data (like
application/x-www-form-urlencoded), PHP's$_POSTwill pick up your variables automatically. - If you're sending raw JSON in the request body, replace the
$_POSTlines with this to read the data:$postData = json_decode(file_get_contents('php://input'), true); $newLevelRecord = [ 'completed_level' => $postData['completed_level'] ?? '', 'user_score' => $postData['user_score'] ?? '', 'player_id' => $postData['player_id'] ?? '' ];
内容的提问来源于stack exchange,提问作者Faizy Zaidy

