从循环 PHP 内的 MySQL 单元创建变量


Create Variable from MySQL Cell Inside Loop PHP

我希望标题足以满足这个问题的内容......

我从各种来源拼凑了一个小脚本,将MySQL数据库中的每一行写入一个单独的XML文件。 它做了它应该做的事情,但是我挂断了命名约定。

我想从正在导出的行的"id"列中命名 XML 文件,其中 $id 是无扩展名的文件的名称。

尝试通过 xpath 访问它无济于事。

如何访问特定列的数据(单元格)并将其分配给变量?

<?php
$host       = "";
$user       = "";
$pass       = "";
$database   = "";
// Replace by a query that matches your database
$SQL_query = "SELECT * FROM data";
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
//ROWS
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {    
  $id;
  $XML = "<?xml version='"1.0'"?>'n";
  $XML .= "<order>'n";
  $XML .= "'t<item>'n"; 
  $i = 0;
  // cells
  foreach ($row as $cell) {
    // Escaping illegal characters - not tested actually ;)
    $cell = str_replace("&", "&amp;", $cell);
    $cell = str_replace("<", "&lt;", $cell);
    $cell = str_replace(">", "&gt;", $cell);
    $cell = str_replace("'"", "&quot;", $cell);
    $col_name = mysql_field_name($result,$i);
    // creates the "<tag>contents</tag>" representing the column
    $XML .= "'t't<" . $col_name . ">" . $cell . "</" . $col_name . ">'n";
    $i++;
  }
  $XML .= "'t</item>'n";
  $XML .= "</order>'n";
  $handle = fopen($id.'.xml','w+');
  fwrite($handle,$XML);
  fclose($handle); 
 }
?>

我设法在谷歌上花了几个小时,并使用XMLWriter重写了它:

<?php
$host       = "";
$user       = "";
$pass       = "";
$database   = "";
mysql_connect($host, $user, $pass) or die ("Could not connect to host.");
mysql_select_db($database) or die("Could not find or access the database");
$sql = "SELECT * FROM data";
$res = mysql_query($sql) or die ("Data not found. Your SQL query didn't work...");
//start document
while ($row = mysql_fetch_assoc($res)) {
    //use this variable for filename later
    $name = $row['id'];
    $xml = new XMLWriter();
    $xml->openMemory();
    $xml->startDocument('1.0', 'UTF-8');
    $xml->setIndent(true);
    $xml->startElement('order');    
    $xml->startElement('item');
    foreach($row as $key => $value) {
        $xml->writeElement($key,$value);
    }
    //$xml->writeElement('id',$row['id']);
    $xml->endElement(); 
    $xml->endElement();

    //close document
    $xml->endDocument();
    file_put_contents($name .'.xml', $xml->outputMemory());
}
?>