如何从我的iPhone应用程序获取html文件的内容(JSON对象)?

时间:2012-01-22 11:44:55

标签: php iphone mysql json

我有一个iPhone应用程序从php文件获取响应。此响应生成一个html文件,其中正文包含一个json对象。如何检索此JSON对象?

$query = "SELECT username FROM userData WHERE username = '$username'";  
    $result = mysql_query($query);  
    if (mysql_num_rows($result) > 0) { 
        sendResponse(200, json_encode('SUCCESS Notification'));
    } else { 
    $query = "INSERT INTO userData (username,password,email,signup_date) VALUES ('$username','$password','$email','$date')";
    $result=mysql_query($query,$connection) or die (mysql_error()." Kann Tabelle der Datenbank nicht lesen!");
    }  

    function sendResponse ($status = 200, $body ='', $content_type = 'application/json'){
            $status_header = 'HTTP/1.1 ' . $status . ' ' . 'OK';
            header($status_header);
            header('Content-type:' . $content_type);
            echo $body;
        }

这是我的iphone应用程序中发生的事情:

 NSURLResponse *theResponse =[[NSURLResponse alloc]init];
        NSError *error;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];      

         NSDictionary *jsonDictionaryResponse =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSLog(@"json response = %@", jsonDictionaryResponse);

3 个答案:

答案 0 :(得分:1)

据我所知,您不会在JSON enocded字符串周围添加HTML-Tags。所以你可以解析整个响应体。我建议您使用jQuery(如果您还没有)或JSON library

但请注意,在发送JSON数据时,您应该将MIME类型转换为application/json,并且对json_encode字符串没有意义。

sendResponse(200, json_encode(array('SUCCESS Notification')), 'application/json');

答案 1 :(得分:0)

如果它是格式正确的HTML(带有开始和结束标记),那么您可以使用任何XML解析器(如NSXMLParser)或使用HPPLE解析器来解析HTML。

答案 2 :(得分:0)

我不确定您发送带有JSON的HTML文件的目的,但这不是一个好习惯。 HTML是一个文档,JSON是一个数据结构,您现在将其作为正文中的文本包含在内。你只是使用响应中的JSON并“抛弃其余部分”吗?因此我同意Pekka改变你的输出。我不确定你对PHP的熟悉程度,但你可以将页面的输出更改为你想要的任何东西。只是不要在你要求的php文件中放入任何html,并将ouput-type设置为json,如下所示:

header('Content-type:text/json');

否则你也可以使用正则表达式或Pekka建议的DOM解析器。