douniwan_0025 2011-10-20 15:19
浏览 28
已采纳

PHP:如何从iPad应用程序接收JSON数组

Disclaimer: I am fairly new to using json.

I am trying to use php to receive json data from an iPAd application. I know how to convert json to an array in php, but how do I actually receive it and store it into a variable so it can be decoded?

Here are a couple examples that I have tried based on google and stackoverflow searches.

$json_request = @file_get_contents('php://input'); 
$array = json_decode($json_request);

AND ALSO

$array = json_decode($_POST['data'], true);

Any suggestions?

  • 写回答

1条回答 默认 最新

  • douceng7070 2011-10-20 15:25
    关注

    You have the basic idea already.

    you should test that the value is set and also strip extra slashes from the incoming string before trying to parse it as JSON.

    if(isset($_POST['data'])){
      $array = json_decode(stripslashes($_POST['data']),true);
      //$array now holds an associative array
    }//Data Exists
    

    It also would not be a bad idea before you start working with the array to test that the call to json_decode() was successful by ensuring that $array isn't null before use.

    If you do not fully trust the integrity of the information being sent you should do extended checking along the way instead of trusting that a given key exists.

    if($array){ // Or (!is_null($array)) Or (is_array($array)) could be used
      //Process individual information here
    
      //Without trust
      if(isset($array['Firstname'])){
        $CustomerId = $array['Firstname'];
      }//Firstname exists
    }//$array is valid
    

    I in-particular like to verify information when I am building queries dynamically for information that may not be required for a successful db insert.

    In the above example $_POST['data'] indicates that what ever called the PHP script did so passing the JSON string using the post method in a variable identified as data.

    You could check more generically to allow flexibility in the sending method by using the $_REQUEST variable, or if you know it is coming as via the get method you can check $_GET. $_REQUEST holds all incoming parameters from both get and post.

    If you don't know what the name of the variable coming in is and want to play really fast and loose you could loop over the keys in $_REQUEST trying to decode each one and use the one that successfully decoded (if any). [Note: I'm not encouraging this]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题