Python Requests发嵌套字典至PHP服务:内容丢失+格式异常求助
Let’s walk through why your nested Python dictionary is arriving as a broken array in PHP, and how to fix it. This is a common gotcha when working with JSON across languages—let’s break it down step by step.
1. First, Make Sure Your Python Request is Sending JSON Correctly
The most common mistake here is not setting the right headers or using the wrong parameter in requests.post. If you use data= instead of json=, Python won’t automatically set the Content-Type: application/json header, which PHP needs to recognize the payload as JSON.
Correct Python Code:
import requests # Your large nested dictionary big_dict = { "top_level_key": "sample_value", "nested_section": { "inner_key": "inner_value", "inner_list": ["item1", "item2", "item3"] } } # Use the `json=` parameter—this auto-sets the required Content-Type header response = requests.post("http://localhost/your_php_script.php", json=big_dict) # Debug: Check what PHP sends back print(response.text)
If You Need to Use data= (Less Ideal):
If you’re manually serializing the JSON, explicitly set the header to avoid confusion:
import json import requests headers = {"Content-Type": "application/json"} response = requests.post( "http://localhost/your_php_script.php", data=json.dumps(big_dict), headers=headers )
Without that header, PHP will treat your JSON as form data, which flattens nested structures or truncates large payloads.
2. Fix PHP’s JSON Receiving Logic
PHP doesn’t automatically populate $_POST for JSON requests—you have to read the raw input stream and decode it yourself. If you’re trying to use $_POST directly, that’s why you’re getting a broken array with missing nested elements.
Correct PHP Code:
<?php // Verify the request is JSON if ($_SERVER['CONTENT_TYPE'] === 'application/json') { // Read the raw JSON payload $raw_input = file_get_contents('php://input'); // Decode into an associative array (preserves nested structures) $data = json_decode($raw_input, true); if ($data === null) { // Handle invalid JSON (e.g., truncated data) http_response_code(400); echo json_encode(["error" => "Invalid JSON: " . json_last_error_msg()]); exit; } // Now $data has your full nested structure—use it as needed var_dump($data); // For debugging } else { http_response_code(400); echo json_encode(["error" => "Request must be in JSON format"]); } ?>
Using json_decode($raw_input, true) gives you an associative array with all nested elements intact. Omit the true parameter if you prefer an object instead.
3. Adjust PHP Configuration for Large Data
Since you’re sending a large dictionary, XAMPP’s default PHP settings might be truncating the payload. Update these values in your php.ini file:
- post_max_size: Set to a value larger than your JSON payload (e.g.,
64Minstead of the default8M). - upload_max_filesize: Should match or exceed
post_max_size. - memory_limit: Ensure PHP has enough memory to process the large array (e.g.,
128M).
Where to Find php.ini in XAMPP:
- Windows:
xampp/php/php.ini - macOS/Linux:
/opt/lampp/etc/php.ini
After making changes, restart Apache from the XAMPP control panel for them to take effect.
4. Quick Debugging Tips
- In Python: Print
response.textto see exactly what PHP sends back. If you get an "invalid JSON" error, your payload is likely being truncated. - In PHP: Add
var_dump($raw_input)before decoding to check if the full JSON is arriving. If it’s cut off, you need to increase the PHP config limits mentioned above.
内容的提问来源于stack exchange,提问作者Bhaskar Pramanik

