我目前正在使用以下脚本打印json文件
<?PHP
include ('connect.php');
$get_student = mysql_query("SELECT * FROM student ORDER BY name asc");
$anArray = json_decode ($data);
while ($row = mysql_fetch_assoc($get_student)) {
$anArray[] = $row;
}
header("Content-type: application/json");
echo json_encode ($anArray, JSON_PRETTY_PRINT)
?>
然后我使用AFNETWORKING在xcode中获取json文件并将其保存到文档目录
url = [NSURL URLWithString:@"url/Json3.php"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFHTTPRequestOperation *downloadOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"database"];
downloadOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[downloadOperation start];
然后我试图读取下载的文档作为JSON文件与以下
NSURL *JsonUrl = [NSURL fileURLWithPath:path];
NSURLRequest *JSONrequest = [[NSURLRequest alloc] initWithURL:JsonUrl];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:JSONrequest success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
anArray = JSON;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
然而,AFNetworking在日志
中给了我以下错误行Request Failed with Error: ErrorDomain =AFNetworkingErrorDomain Code=-1016 "期望的内容类型{("文本/json","application/json","text/javascript")},得到text/plain" UserInfo=0xa49f990 {NSLocalizedRecoverySuggestion=[
,然后显示日志
中的文本文档内容。我如何使PHP JSON打印,打印应用程序/JSON文档,而不是文本文档?
谢谢
假设这是一个头已经发送的问题,在你的"connect.php",在最顶部,放
ob_start();
这将启动outbut缓冲,这基本上意味着php不会向浏览器发送任何内容,直到所有内容都被渲染(或者直到缓冲区被发送,停止等)
如果你想把数据保存到json文件中,你可以使用
file_put_contents('myfile.json', json_encode($anArray, JSON_PRETTY_PRINT));
另外,传递给json_encode函数的标志也可能有问题。只是一个想法。
检查connect.php的内容,php结束标记后没有空格,或者直接删除?>
好吧,它没有解决打印问题,但一个简单的代码行使它工作
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
希望这对有类似问题的人有帮助