2013-04-08 51 views
0

我目前使用下面的脚本打印JSON文件保存为JSON文件用PHP打印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]; 

我再尝试读取下载的文档具有下列

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]; 
一个JSON文件10

然而AFNetworking给我在日志以下错误线

请求失败,错误:错误域= AFNetworkingErrorDomain代码= -1016“预期内容类型{( “文本/ JSON”, “应用/ JSON”, “文本/ JavaScript的” )},得到纯文本/”的UserInfo = 0xa49f990 {NSLocalizedRecoverySuggestion = [

,然后示出了日志

QUESTION

0在文本文档内容

如何进行PHP JSON打印,打印Application/Json文档而不是文本文档?

感谢

+2

我猜在发送'header('Content-Type:application/json');'在PHP中发生错误。 – hek2mgl 2013-04-08 13:30:17

+1

检查_“头已发送”_警告。 – Halcyon 2013-04-08 13:32:41

+0

@FritsvanCampen我已经检查过头文件,并且可以确认它们尚未发送 – Tom 2013-04-10 08:29:55

回答

0

假设它已经发送问题头,在你的“connect.php”,在最高层,把

ob_start(); 

这将启动outbut缓冲这基本上意味着,PHP犯规发送任何东西到浏览器,直到所有东西都呈现(或直到缓冲区被发送,停止等)。

如果其他东西只是想将数据保存到json文件中,可以使用

file_put_contents('myfile.json', json_encode($anArray, JSON_PRETTY_PRINT)); 

此外,它可能是您传递给json_encode函数的标志有问题。只是一个想法。

+0

感谢您的回复@Ozzy,我已经尝试了上述内容,但没有成功。事实上,file_put_contents以正确的格式打印JSON文件,但将其作为单独的身份保存在服务器上。什么即时通讯尝试实现的是让php脚本打印第一个实例中的正确文档 – Tom 2013-04-10 08:28:05

0

检查connect.php的内容,没有空间是php结束标签之后,或者只是删除?>

+0

感谢您的答复大卫,但在检查连接文档后,我可以确认没有空格在PHP文档的末尾 – Tom 2013-04-10 08:29:18

0

好吧,我没有解决打印问题,而是一个简单的代码行使工作

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]]; 

希望这可以帮助有类似问题的人