PHP JSON转换为变量

时间:2018-07-20 17:08:12

标签: php json

我不明白。我正在通过C#发送JSON,而我的MySQL服务器上的PHP正在捕获它,但是通常在发布时捕获,现在我应该使用json_decode捕获它,但是即使我也可以看到数据并打印出来。

我似乎无法将其转换为可用的格式以插入数据库:

Array print out using print_r ($data); looks like this 

/Array
(
    [widget1] => 54
     [widget2] => tttt
    [widget3] => tttttttt
   [widget4] => 100
   [widget5] => 3
    [imageobject] => /9j/4QPqRXhpZgAATU0AKgAAAAgADAEbAAUAAAABAAAAngEaAAUAAAABAAAApgEAAAQAAAABAAAFUwEQAAIAAAAJAAAArgExAAIAAAAOAAAAtwEPAAIAAAAIAAAAxQEBAAQAAAABAAAD8wITAAMAAAABAAEAAIdpAAQAAAABAAAA4QESAAMAAAABAAAAAAEoAAMAAAABAAIAAAEyAAIAAAAUAAAAzQAAA3gAAABIAAAAAQAAAEgAAAABU00tRzk1NUYARzk1NUZYWFUyQ1JGNwBzYW1zdW5nADIwMTg6MDc6MTkgMTY6NDc6MjEAACCSAgAFAAAAAQAAAmeQAAAHAAAABDAyMjCSBAAKAAAAAQAAAm+IIgADAAAAAQACAACkIAACAAAAGQAAAnegAQADAAAAAQABAACSBQAFAAAAAQAAApCgAwADAAAAAQH5AACSAwAKAAAAAQAAApiQAwACAAAAFAAAAqCgAAAHAAAABDAxMDCSfAAHAAAAYgAAArSSkQACAAAABQAAAxakAwADAAAAAQAAAACgBQAEAAAAAQAAA2akAgADAAAAAQAAAACCmgAFAAAAAQAAAxuSCQADAAAAAQAAAACSkAACAAAABQAAAyOCnQAFAAAAAQAAAyiIJwADAAAA)

我试图将数据访问如下所示的变量,这显然是错误的

<?php
header('Content-Type: application/json;charset=utf-8');

require "connect.php";


//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json; charset=utf-8') != 0){
   throw new Exception('Content type must be: application/json '.$contentType);

}

//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));

//Attempt to decode the incoming RAW post data from JSON.
$data = json_decode($content, true);

//If json_decode failed, the JSON is invalid.
if(!is_array($data)){
    throw new Exception('Received content contained invalid JSON!');
}

print_r ($data);

$Widget1= $data[0]->widget1; 
$Widget2= $data[0]->widget2; 
$Widget3= $data[0]->widget3; 
$Widget4= $data[0]->widget4; 
$Widget5= $data[0]->widget5; 
$Widget6= $data[0]->imageobject; 

1 个答案:

答案 0 :(得分:0)

所以Alex是对的,这解决了我的问题$ Widget1 = $ data ['widget1'];