PHP:如何从 JSON 中获取变量(从 Swift iOS 应用程序发送)并以 JSON 响应

Posted

技术标签:

【中文标题】PHP:如何从 JSON 中获取变量(从 Swift iOS 应用程序发送)并以 JSON 响应【英文标题】:PHP: how to get variables from a JSON(sent from a Swift iOS app) and respond with a JSON 【发布时间】:2015-05-14 08:24:12 【问题描述】:

我正在使用 Swift 开发一个 ios 应用程序,它应该根据用户的位置从 mysql 数据库中获取一些数据。我不懂 php,也找不到解释如何从应用程序接收数据的资源。

我有这个 PHP 代码:

<?php

// Create connection
$con=mysqli_connect("localhost","*******","*******","*******");

// Check connection
if (mysqli_connect_errno())

  echo "Failed to connect to MySQL: " . mysqli_connect_error();


// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM *******";

// Check if there are results
if ($result = mysqli_query($con, $sql))


    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    

    // Finally, encode the array to JSON and output the results
    echo " \"posts\": ";
    echo json_encode($resultArray);
    echo "";


// Close connections
mysqli_close($con);
?>

正如你所看到的,当它被调用时,它会从一个表中获取所有数据并将其作为 JSON 返回。我要做的下一步是使用以下代码从 Swift 应用程序发送我的位置:

@IBAction func submitAction(sender: AnyObject) 

            //declare parameter as a dictionary which contains string as key and value combination.
            var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>

            //create the url with NSURL 
            let url = NSURL(string: "http://myServerName.com/api") //change the url

            //create the session object 
            var session = NSURLSession.sharedSession()

            //now create the NSMutableRequest object using the url object
            let request = NSMutableURLRequest(URL: url!)
             request.HTTPMethod = "POST" //set http method as POST

            var err: NSError?
            request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")

            //create dataTask using the session object to send data to the server
            var task = session.dataTaskWithRequest(request, completionHandler: data, response, error -> Void in
                println("Response: \(response)")
                var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Body: \(strData)")
                var err: NSError?
                var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

                // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                if(err != nil) 
                    println(err!.localizedDescription)
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: '\(jsonStr)'")
                
                else 
                    // The JSONObjectWithData constructor didn't return an error. But, we should still
                    // check and make sure that json has a value using optional binding.
                    if let parseJSON = json 
                        // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                        var success = parseJSON["success"] as? Int
                        println("Succes: \(success)")
                    
                    else 
                        // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                        let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                        println("Error could not parse JSON: \(jsonStr)")
                    
                
            )

            task.resume()
        

感谢http://jamesonquave.com/blog/making-a-post-request-in-swift/

我不知道如何“获取”(接受,使用什么函数)这个 JSON:

"items": [
            
                "minLat": "43.000000",
                "maxLat": "44.000000",
                "minLon": "-79.000000",
                "maxLon": "-78.000000",
            
          ]
    

为了在 PHP 中有这样的东西:

$minLat = $json['minLat'];
$maxLat = $json['maxLat'];
$minLon = $json['minLon'];
$maxLon = $json['maxLon'];

$sql = "SELECT * FROM ******* WHERE latitude BETWEEN".$minLat." AND ".$maxLat." AND longitude BETWEEN ".$minLon." AND ".$maxLon;

谢谢

【问题讨论】:

嗨 Andrei,最简单的方法是您必须在服务器中创建 index.php 文件,并在您的 swift 应用程序中指定 myServerName.com/index.php url,在 php 文件中获取请求,如 if (isset($_POST["your_key_here"])) $json = json_decode($_POST["your_key_here"]); 你需要使用 Alamofire 和 SwiftyJSON。 我的 Swift 代码没有问题!!我有它的 PHP @styopdev 感谢您的回复,但是如果 (isset($_POST["your_key_here"])) 中的“your_key_here”应该是什么?我不使用表格。 【参考方案1】:

答案实际上非常简单:

在我评论这两行之前,首先没有任何效果:

request.addValue("application/json", forHTTPHeaderField: "Content--Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

然后我使用字符串而不是 JSON 来发送 POST 数据(它当然也可以与 JSON 一起使用,但这就是目前的工作方式):

let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";

let postString = "minLat=43.0&maxLat=44.0&minLon=26.0&maxLon=27.0";

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

在服务器端:

$minLat = $_REQUEST["minLat"];
$maxLat = $_REQUEST["maxLat"];
$minLon = $_REQUEST["minLat"];
$maxLon = $_REQUEST["maxLat"];

:|

【讨论】:

以上是关于PHP:如何从 JSON 中获取变量(从 Swift iOS 应用程序发送)并以 JSON 响应的主要内容,如果未能解决你的问题,请参考以下文章

如何从 PHP 中获取 JSON 值?

如何在php中将json数组值声明为变量

如何从 php 获取数据表 jquery 插件的 json 数据

如何从 php 脚本中获取 JSON 格式的 mysql 表的所有值?

如何从 php 页面(没有 json)获取数据?

如何使用 php 从 json 获取特定的电子邮件数据