Xml和json接口

<?php
// json格式接口调用http://www.cishop.com/jiekou/jiekou.php?name=要传的值&format=json
// XML格式接口调用http://www.cishop.com/jiekou/jiekou.php?name=要传的值&format=xml
$name=isset($_GET['name'])?$_GET['name']:"河南";
header('content-type:text/html;charset=utf-8');
$pdo=new PDO('mysql:host=127.0.0.1;dbname=ecshop','root','root',array(PDO::MYSQL_ATTR_INIT_COMMAND=>'set names utf8'));
$arr=$pdo->query("select * from address where ad_name='$name'");
$arr->setFetchMode(PDO::FETCH_ASSOC);
$ar=$arr->fetchAll();
//xml格式的接口
if($_GET['format']=='xml'){
    header('content-type:application/xml;charset=utf-8');
    echo '<?xml version="1.0" encoding="utf-8" ?>';
    echo '<nod>';
    foreach($ar as $key=>$val){
        echo "<nod".$key.'>';
        foreach($val as $k=>$v){
            echo "<".$k.'>';
            echo $v;
            echo "</".$k.'>';
        }
        echo "</nod".$key.'>';
    }
    echo '</nod>';
}elseif($_GET['format']=='json'){
    //json格式的接口
    echo json_encode($ar);
}

你可能感兴趣的:(Xml和json接口)