如何在php中将数组作为xml响应发送

时间:2013-09-25 11:46:59

标签: php xml arrays

我想发送xml响应。我试过以下代码。但不打印数组元素,只打印“数组”。请告诉我我哪里错了?

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("video_link");

    try {   
        $query = "select * from upload_video";
        $result = mysql_query($query);

    }
    catch(Exception $ex) {

        $response = '<?xml version="1.0" encoding="utf-8"?>';
            $response .= '<response><status>'.'0'.'</status>';
        $response = $response.'<remarks>'.'Error'.'</remarks></response>';
        header("Content-type: text/xml; charset=utf-8");
        echo $response;
    }

    $n = mysql_num_rows($result);

    for($i=0; $i < $n; $i++) {
        $url = mysql_result($result,$i,'url');

        $store[] = array("url" => $url);     

            }

            $response = '<?xml version="1.0" encoding="utf-8"?>';
            $response .= '<response><status>'.'1'.'</status>';
        $response = $response.'<remarks>'.$store.'</remarks></response>';
        header("Content-type: text/xml; charset=utf-8");
        echo $response;

?>

1 个答案:

答案 0 :(得分:0)

如果您希望列表项为XML节点,请使用此选项来编写您认为合适的XML而不是for循环:

$list = "";
for($i=0; $i < $n; $i++) {
    $url = mysql_result($result,$i,'url');
    $list .= "<item>".$url."</item>";
 }

如果逗号分隔列表足够,只需在$ store数组中使用implode:

$response = $response.'<remarks>'.implode(", ", $store).'</remarks></response>';