2013-06-06 51 views
1

我正在使用一個工具將一些數據從數據庫導出到文本文件。下面的代碼給出:安排使用PHP的文本文件

$query3=mysql_query("SELECT * FROM records WHERE domain_id=".$domainID." AND type='NS' ORDER BY id ASC, name ASC"); 
    while($result3 = mysql_fetch_array($query3)) 
    { 
     $type=$result3['type']; 
     $content=$result3['content']; 
     $result = $result3['name']; 
     $length = strlen(".".$domainNAME); 
     $string = substr($result, 0, $length*(-1)); 
     fwrite($fh,$string."     IN NS ".$content."\n"); 

    } 

所以輸出文本文件的一個是這樣的:

       IN NS ns1.example.net. 

team.example.net.     IN NS ns1.example.net. 

team.example.net.     IN NS ns2.example.net. 

teamex01.example.net.     IN NS ns1.example.net. 

teamex01.example.net.     IN NS ns2.example.net. 

dev.example.net.     IN NS ns1.example.net. 

dev.example.net.     IN NS ns2.example.net. 

我要輸出如文件:

        IN NS ns1.example.net. 

team.example.net.     IN NS ns1.example.net. 

team.example.net.     IN NS ns2.example.net. 

teamex01.example.net.    IN NS ns1.example.net. 

teamex01.example.net.    IN NS ns2.example.net. 

dev.example.net.     IN NS ns1.example.net. 

dev.example.net.     IN NS ns2.example.net. 

我要安排一下按列。 IN NS記錄應該安排在一列中。有什麼辦法來安排文件?

謝謝!

回答

0

$string使用str_pad()

$string = str_pad(substr($result, 0, $length*(-1)), 6, ' ', STR_PAD_RIGHT); 

這將多達六個空格添加到字符串確保它的末端是一個統一的長度。

(該6是任意根據您在上面提供的樣品。你需要了解哪些值最適合你的。)

+0

我試過了str_pad。但沒有效果! – NewPHP

1

要做到這一點,你需要在整個預迭代列表中以獲得第一列中的最長字符串長度爲strlen(),然後在輸出時使用str_pad()以使其「非常好」。

嘗試是這樣的(粗略的概念):

$results = array(); 
$longestLength = 0; 
// loop through the mysql results, store them in a `results`-array and save the longest-name 
while($result = mysql_fetch_array($query)) { 
    $results[] = $result; 
    if (($strlen = strlen($result['name'])) > $longestLength) $longestLength = $strlen; 
} 

// loop through all of the results and output with the desired format 
foreach ($results as $result) { 
    echo sprintf("%s\tIN NS %s\n", str_pad($result['name'], $longestLength), $result['content']); 
} 

側面說明(不是回答具體):
建議不使用舊的,在PHP中棄用mysql擴展,而使用的青睞mysqliPDO擴展名。兩者都提供了額外的功能,例如準備語句,並且對SQL注入攻擊也更加安全!