2014-12-06 70 views
0

創建變量,我希望冠軍是足夠的問題的內容...從MySQL細胞內環路PHP

我拼湊來自不同源的小腳本,在MySQL數據庫中寫入每一行一個單獨的XML文件。它做它應該做的事,但是我掛在命名約定上。

我想從正在導出的行的'id'列中命名XML文件,其中$id是文件sans擴展名。

試圖通過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); 
} 

?> 
+0

你真的應該使用PHP內置XML功能,而不是手動構建XML。 – 2014-12-06 00:52:40

+0

謝謝 - 我已經使用XMLWriter重建了所有東西,並使其工作 – 2014-12-08 17:29:04

回答

0

我好不容易花時間在谷歌和改寫了這一點使用的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()); 
} 
?>