You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用json_decode无法访问对象属性值问题求助

解决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 no return statement)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:26:27