I am trying to send json array to php and insert multiple rows in to table
Problem:
Php:
- Not able to access the decode JSON array - array count returns nil
- Warning: Invalid argument supplied for foreach()
When I print JSON string it gives me the below data
[
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"ontact1" : ""
},
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"contact1" : ""
},
{
"email" : "",
"Name" : "Dddddr",
"contact2" : "",
"contact1" : ""
}
]
But when I am trying to access that using php that shows me a error
PHP CODE:
<?php
$inputJSON = file_get_contents('php://input');
$array = json_decode($inputJSON, true);
echo count($array);
foreach($array as $item) {
$uses = $item['Name'];
echo $uses;
}
?>
Error:
Warning: Invalid argument supplied for foreach()
So I tested the array in php using ,
Isarray() || Isobject funtion but it print null
Count() funcions provide 0
var_dump($array); result NULL
But I decode the array and check the result in iOS, it gives the array as response
echo json_encode($array);
But in php I am not able access the array.
Not sure if there is any mistake in iOS code. In iOS I have NSMutableDictionary that is stored to NSMutableArray and then NSArray.
When I parse the NSMutableArray I get the same problem.
iOS code:
func saveToCloud(){
var mutablearray = NSMutableArray()
var dict = NSMutableDictionary()
var eachRow = textfieldarry as [UITextField]
for eachField in eachRow {
let index = eachRow.indexOf(eachField)
let data = eachField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
dict[keys[index!]] = data
}
mutablearray.addObject(dict)
var TonNSarray = NSArray(array: mutablearray)
var url = "myurl/file.php "
JsonParseTOSaveCloud(TonNSarray, urlstring: url, successfullResponse: "Success", alertmessage: "not")
}
Saving to Server:
func ok_JsonParseTOSaveCloud(dict:AnyObject,urlstring:String,successfullResponse:String,alertmessage:String){
let json:NSData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
var d = NSString(data: json, encoding: NSUTF8StringEncoding)
print("jsonstr\(d!)")
let urlString = urlstring
urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())!
let httpRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
httpRequest.HTTPMethod = "POST"
httpRequest.HTTPBody = json
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfig.HTTPAdditionalHeaders = ["Accept" : "application/json", "api-key" : "API_KEY"]
let session = NSURLSession(configuration: sessionConfig)
let postDataTask = session.dataTaskWithRequest(httpRequest, completionHandler: {(data: NSData?, reponse: NSURLResponse?, error: NSError?) in
if data == nil {
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertView(title: alertmessage, message: "you are no longer connected to the Internet", delegate: self, cancelButtonTitle: "Dismiss")
alert.show()
})
} else {
print("data\(data)")
//let jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers))
}
})
postDataTask.resume()
}
Note: When I check in php, like this it works. That is when I give the Jsonstring or jsonarray directly it works.
<?php
$json = '[
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"contact1" : ""
},
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"contact1" : ""
},
{
"email" : "",
"Name" : "Dddddr",
"contact2" : "",
"contact1" : ""
}
]';
$array = json_decode( $json, true );
foreach($array as $item) {
$uses = $item['Name'];
echo $uses;
}
?>
var_dump($inputJSON)and make sure there's nothing extra in the input. Also usejson_last_error()whenjson_decode()returnsNULL.