0

我想将我的 mysql 查询转换为XML,为此我使用了本教程的代码:http: //www.codediesel.com/php/converting-mysql-queries-to-xml/我必须将其自定义为使用PDO代替mysql函数。这是代码:

function sqlToXml($queryResult, $rootElementName, $childElementName)
{ 
    $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"; 
    $xmlData .= "<" . $rootElementName . ">";

    while($record = $queryResult->fetch(PDO::FETCH_OBJ))
    { 
        /* Create the first child element  */
        $xmlData .= "<" . $childElementName . ">";

        for ($i = 0; $i < $queryResult->columnCount(); $i++)
        { 
            $fieldName = $queryResult->getColumnMeta($i);

            /* The child will take the name of the table column  */
            $xmlData .= "<" . $fieldName . ">";

            /* We set empty columns with NULL, or you could set 
                it to '0' or a blank. */
            if(!empty($record->$fieldName))
                $xmlData .= $record->$fieldName; 
            else
                $xmlData .= "null"; 

            $xmlData .= "</" . $fieldName . ">"; 
        } 
        $xmlData .= "</" . $childElementName . ">"; 
    } 
    $xmlData .= "</" . $rootElementName . ">"; 

    return $xmlData; 
}

但是当我尝试执行代码时出现此错误:注意:第42/opt/lampp/htdocs/promos/t.php中的数组到字符串转换

注意:第42/opt/lampp/htdocs/promos/t.php中的数组到字符串转换

注意:第42/opt/lampp/htdocs/promos/t.php中的数组到字符串转换

注意: /opt/lampp/htdocs/promos/t.php中第42行的数组到字符串的转换nullnullnullnull

42行是:

if(!empty($record->$fieldName))

你对此有什么想法吗?谢谢 :)

4

2 回答 2

0

您需要字段名,因此您必须从getColumnMeta()返回的关联数组中检索它,您错误地认为它返回了一个字符串,因此只需替换以下行:

$fieldName = $queryResult->getColumnMeta($i);

对于这个:

$fieldName = $queryResult->getColumnMeta($i);
$fieldName = $fieldName['name'];

这应该$fieldName包含字段名称,因此您的其余代码将起作用。

于 2012-11-12T16:20:38.543 回答
-1

函数 getColumnMeta 返回一个数组。不是字符串。除此之外,它被标记为实验性的。在它变得更加稳定之前,我不会在生产代码上使用它。

但我认为这应该有效

function sqlToXml($queryResult, $rootElementName, $childElementName)
{ 
    $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"; 
    $xmlData .= "<" . $rootElementName . ">";


    while($record = $queryResult->fetch(PDO::FETCH_OBJ))
    { 
        /* Create the first child element  */
        $xmlData .= "<" . $childElementName . ">";

        for ($i = 0; $i < $queryResult->columnCount(); $i++)
        { 
            $colum = $queryResult->getColumnMeta($i);
            $fieldName = $column['name'];

            /* The child will take the name of the table column  */
            $xmlData .= "<" . $fieldName . ">";

            /* We set empty columns with NULL, or you could set 
                it to '0' or a blank. */
            if(!empty($record->$fieldName))
                $xmlData .= $record->$fieldName; 
            else
                $xmlData .= "null"; 

            $xmlData .= "</" . $fieldName . ">"; 
        } 
        $xmlData .= "</" . $childElementName . ">"; 
    } 
    $xmlData .= "</" . $rootElementName . ">"; 

    return $xmlData; 
}
于 2012-11-12T16:20:33.560 回答