PHP使用json_decode无法访问对象属性值问题求助
Got it, let's break down why your json_decode isn't working as expected here.
核心问题分析
Your UploadImages() function uses echo to output the JSON string instead of returning it as a function value. When you call UploadImages() in Caller.php:
- The JSON gets printed directly to the output stream immediately
- The function itself returns
null(since there's noreturnstatement)
So json_decode(null, true) gives you null, which is why you can't access keys like ["UploadOk"] or ["UploadMsg"].
修复方案
Modify the UploadImages() function to return the JSON string instead of echoing it:
修改后的 UploadImages.php
<?php function UploadImages(){ $result = [ "UploadOk" => 0, "UploadMsg" => "Upload successful" ]; return json_encode($result); // Replace echo with return } ?>
调用端 Caller.php(无需额外修改,现在可以正常工作)
<?php include "UploadImages.php"; $uploadResult = json_decode(UploadImages(), true); if($uploadResult["UploadOk"] == 1) { // do something else } else { echo $uploadResult["UploadMsg"]; // Will now correctly output "Upload successful" } ?>
额外场景说明
If you need UploadImages() to both return the JSON for processing and output it (e.g., for an API response), you can do both by returning first, then echoing the returned value when needed:
// In an API endpoint file include "UploadImages.php"; $jsonResponse = UploadImages(); echo $jsonResponse; // Outputs the JSON to the client // You can also process $jsonResponse further if needed
This fixes your issue because we're now passing a valid JSON string to json_decode instead of null.
内容的提问来源于stack exchange,提问作者Erwin Sanders

