我正在尝试使用以下代码生成BLOB数据(来自MySQL的GIF图像)。我收到'文字内容中发现了无效字符'。如果有任何建议,请告诉我吗?
$connection = mysql_connect( $db_host, $db_username, $db_password );
$result = mysql_query("SELECT * from files");
header("Content-Type: application/xml");
echo sqlToXml($result, "entries", "entry");
function sqlToXml($queryResult, $rootElementName, $childElementName) {
$w = new XMLWriter();
$w->openMemory();
$w->setIndent(true);
// use tabs as indents
$w->setIndentString(" ");
$w->startDocument("1.0", 'UTF-8');
$w->startElement($rootElementName);
while($record = mysql_fetch_object($queryResult)) {
$w->startElement($childElementName);
for ($i = 0; $i < mysql_num_fields($queryResult); $i++) {
$fieldName = mysql_field_name($queryResult, $i);
$w->startElement($fieldName);
if(!empty($record->$fieldName)) {
$w->writeCData(base64_encode($record->$fieldName));
}
else {
$w->writeCData("null");
}
$w->endElement(); // $fieldName
}
$w->endElement();
$w->endElement(); // $childElementName
}
$w->endElement(); // $rootElementName
$w->endDocument();
return $w->outputMemory();
}
答案 0 :(得分:1)
你的内循环非常冗长。为什么不:
while($row = mysql_fetch_assoc($result)) {
$w->startElement($childElementName);
foreach($row as $key => $value) {
$w->startElement($key);
$w->writeCData(base64_encode($value));
}
$w->endElement();
}
另外,请注意empty()
在这种情况下可能会很危险,尤其是如果您的数据自然可以包含整数0
值之类的内容。 PHP中empty(0)
为TRUE。