8

我发现这个很棒的函数可以将 MySQL 查询转换为 XML 页面,它看起来正是我所需要的。唯一的问题是它使用 MySQL,但不再支持它,结果发现其中一个使用的函数不在 MySQLi 中。有谁知道替代方案mysql_field_name

这是我找到的功能

function sqlToXml($queryResult, $rootElementName, $childElementName)
{ 
    $xmlData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n"; 
    $xmlData .= "<" . $rootElementName . ">";
 
    while($record = mysql_fetch_object($queryResult))
    { 
        /* Create the first child element */
        $xmlData .= "<" . $childElementName . ">";
 
        for ($i = 0; $i < mysql_num_fields($queryResult); $i++)
        { 
            $fieldName = mysql_field_name($queryResult, $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; 
}

有问题的部分是

$fieldName = mysql_field_name($queryResult, $i);
4

2 回答 2

22

有很多方法可以做到这一点,我想最相似的是:

$fieldName = mysqli_fetch_field_direct($result, $i)->name;

http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php

于 2013-09-23T03:51:12.127 回答
0

除了@trakos 答案:

如果你喜欢懒惰的方式

由于 mysql_field_name 在 PHP 7 中被删除,请尝试使用文档中提到的替代方法: https ://www.php.net/manual/en/function.mysql-field-name.php

如果您想要同名函数,请尝试实现这个:

function mysqli_field_len($result, $i) {
    $properties = mysqli_fetch_field_direct($result, $i);
    return is_object($properties) ? $properties->name : null;
}
于 2022-01-27T06:12:46.617 回答