Android访问php mysql以json或xml文件输出数据实例源码介绍



Android访问php mysql以json或xml文件输出数据实例源码介绍。Android如何访问apache服务器上的数据库。假如PHP做的服务端,要用Android去访问,PHP的服务端可以以JSON和XML提供返回的数据,而android端则可以用APACHE的httpclient去访问这些数据。

Android访问数据库例子,假设数据表中users表有如下字段(mysql):idusers,UserName,FullName,加点数据.然后在服务端PHP,建立一个webservice1.php,作用是直接返回服务端数据库的数据,如下:

<?php
if(isset($_GET['user']) && intval($_GET['user'])) {
$format = strtolower($_GET['format']) == ‘json’ ? ‘json’ : ‘xml’; //xml is the default
$user_id = intval($_GET['user']); //no default
/* 连接数据库*/
$link = mysql_connect(‘localhost’,'root’,'xxxxx’) or die(‘Cannot connect to the DB’);
mysql_select_db(‘jsonandroid’,$link) or die(‘Cannot select the DB’);
$query = “SELECT * FROM `users`;”;
$result = mysql_query($query,$link) or die(‘Errant query: ‘.$query);
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array(‘post’=>$post);
}
}
/* json格式*/
if($format == ‘json’) {
header(‘Content-type: application/json’);
echo json_encode(array(‘posts’=>$posts));
}
else {
header(‘Content-type: text/xml’);
echo ‘<posts>’;
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo ‘<’,$key,’>’;
if(is_array($value)) {
foreach($value as $tag => $val) {
echo ‘<’,$tag,’>’,htmlentities($val),’</’,$tag,’>’;
}
}
echo ‘</’,$key,’>’;
}
}
}
echo ‘</posts>’;
}
}
?>
则可以把数据表输出为JSON或者XML格式了.客户端的ANDROID调用:

try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpParams p = new BasicHttpParams();
p.setParameter(“user”, “1″);
HttpClient httpclient = new DefaultHttpClient(p);
String url = “http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json”;
HttpPost httppost = new HttpPost(url);
try {
Log.i(getClass().getSimpleName(), “send task – start”);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair(“user”, “1″));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// 解析JSON返回的 JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray(“posts”);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString(“post”);
JSONObject jObject = new JSONObject(s);

map.put(“idusers”, jObject.getString(“idusers”));
map.put(“UserName”, jObject.getString(“UserName”));
map.put(“FullName”, jObject.getString(“FullName”));

mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
在浏览器输入http://www.www/webservice1.php?user=1&format=xml,输出如下:
<posts>
<post>
<idusers>101</idusers>
<UserName>8</UserName>
<FullName>78</FullName>
</post>
</posts>
当然可能也会存在输出是乱码的问题,那就先要将webservice1.php保存成utf-8的格式

如果是直接想在浏览器输出不带参数user=1&format=xml的,并且可以直接以id号输出
<?php
$format = ‘xml’;
/* 连接数据库*/
$link = mysql_connect(‘localhost’,'root’,'****’) or die(‘Cannot connect to the DB’);
$sid = $_GET['sid'];
mysql_select_db(‘gxdzw’,$link) or die(‘Cannot select the DB’);
$query = ‘SELECT * FROM `md_subject` , `md_card_discounts` where md_subject.sid=md_card_discounts.sid and md_subject.sid= ‘.$sid;
mysql_query(“SET NAMES UTF8″);
$result = mysql_query($query,$link) or die(‘Errant query: ‘.$query);
$posts = array();
if(mysql_num_rows($result))
{
while($post = mysql_fetch_assoc($result))
{ //对数组的值进行url编码
foreach ( $post as $key => $value ) {
$post[$key] = urlencode($value);
}
$posts[] = array(‘post’=>$post);
}
}
header(‘Content-type: text/xml’);
echo ‘<posts>’;
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo ‘<’,$key,’>’;
if(is_array($value)) {
foreach($value as $tag => $val) {
//echo ‘<’,$tag,’>’,htmlentities($val),’</’,$tag,’>’;
echo ‘<’,$tag,’>’,urldecode(htmlentities($val,ENT_COMPAT,”UTF-8″)),’</’,$tag,’>’;
}
}
echo ‘</’,$key,’>’;
}
}
}
echo ‘</posts>’;
?>
在浏览器输入http://www.www/webservice1.php?sid=1,输出如下:
<posts>
<post>
<idusers>1</idusers>
<UserName>8</UserName>
<FullName>78</FullName>
</post>
</posts>
在设计数据输出时也可以是带参数的
/* 连接数据库*/
$link = mysql_connect(‘localhost’,'root’,'****’) or die(‘Cannot connect to the DB’);
$startindex = $_GET['startindex'];
$pagesize = $_GET['pagesize'];
$category = $_GET['category'];
$query = ”;
mysql_select_db(‘gxdzw’,$link) or die(‘Cannot select the DB’);
if($category == 0)
{
$query = ‘SELECT * FROM `md_subject` , `md_card_discounts` where md_subject.sid=md_card_discounts.sid and status=1 and discount>0 limit ‘.$startindex.’,’.$pagesize;
}
else{
$query = ‘SELECT * FROM `md_subject` , `md_card_discounts` where md_subject.sid=md_card_discounts.sid and status=1 and discount>0 and pid = ‘.$category.’ limit ‘.$startindex.’,’.$pagesize;
}
浏览器输入http://www.www/webservice1.php?startindex=0&category=1&pagesize=12