2011-10-28 21 views
1

這可能很簡單,但我不知道最好的方法來做到這一點。我使用php從mysqli數據庫中提取數據以創建一個XML文檔。我的代碼如下所示,但標題字段中的數據全部大寫。我只需要大寫的第一個字符,其餘的小寫。我知道我需要ucwords功能,但沒有骰子。標題字段在所有大寫中包含多個單詞。使用php大寫字符串的第一個字符。然後用XMLWriter輸出。

我需要ucwords在進入XML區域之前格式化的數據。我更喜歡在php中這樣做,而不是更新數據庫中的數據。謝謝您的幫助!

<?php 

// Connect to the database 
global $link; 
$link = mysqli_connect("localhost", "root", "pass", "database"); 

// Verify the connection worked 
if (!$link) { 
    printf("Connection to database failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

// Prepare the database query 
    $stmt = mysqli_prepare($link, "SELECT * FROM table"); 

// Run the database query 
    mysqli_stmt_execute($stmt); 

// Bind the result columns to PHP variables 
    mysqli_stmt_bind_result($stmt, $Name, $Title);  

// Create a new XML document in memory 

$xw = new xmlWriter(); 
$xw->openURI('php://output'); 
$xw->openMemory(); 
$xw->startDocument('1.0'); 

// Start the outer data container 
$xw->StartElement('rss'); 
$xw->WriteAttribute('version', '2.0'); 

// Fetch values 
    while (mysqli_stmt_fetch($stmt)) { 

{ 

$xw->startElement('item'); 

    // Write out the elements 
    $xw->writeElement('Name', $Name); 
    $xw->writeElement('Title', $Title); 
    $xw->endElement(); 

} 

// End container 
$xw->endElement(); 

// End the document 
$xw->endDocument(); 


//header('Content-Type: text/xml'); 
print $xw->outputMemory(true); 

// Close the database statement 
mysqli_stmt_close($stmt); 

// Close the database connection 
mysqli_close($link); 
} 
?> 
+0

ucwords(strtolower($ str))? – galchen

+0

對不起,聽起來像一個新手,但我把這個後綁定聲明?那很重要嗎?我加了ucwords(strtolower($ Title));然後在xml輸出中我的Title不會出現。這是什麼讓我絆倒。 –

+0

ucwords和strtolower將返回一個修改過的字符串。他們不會改變原來的價值。如果你做$ Title = ucwords(strtolower($ Title));那麼從這一點開始,$ Title將是修改後的版本。我認爲你想要的是$ xw-> writeElement('Title',ucwords(strtolower($ Title))); – galchen

回答

1

http://php.net/manual/en/function.ucwords.php

<?php 
$foo = 'hello world!'; 
$foo = ucwords($foo);    // Hello World! 

$bar = 'HELLO WORLD!'; 
$bar = ucwords($bar);    // HELLO WORLD! 
$bar = ucwords(strtolower($bar)); // Hello World! 
?> 

爲您的查詢相關的部分,我會代替:

// Prepare the database query 
$stmt = mysqli_prepare($link, "SELECT * FROM table"); 

// Run the database query 
mysqli_stmt_execute($stmt); 

// Bind the result columns to PHP variables 
mysqli_stmt_bind_result($stmt, $Name, $Title);  

有了:

$results = mysqli_query("SELECT * FROM table"); 

然後改變你的while循環:

foreach($results as $row) { 
    $xw->startElement('item'); 
    $xw->writeElement('Name', ucwords(strtolower($row['name'])); 
    $xw->writeElement('Title', ucwords(strtolower($row['title'])); 
    $xw->endElement(); 
} 

很明顯,你需要修補這個,因爲我不知道你的數據庫模式。

更改mysqli的主要原因是,如果將來對數據庫進行模式更改,則不能保證具有相同的數據庫列排序。

祝你好運!

+0

感謝Hafichuk,我遵循的手冊,但新手我似乎無法讓XML部分後來工作。 –

+0

會做,謝謝你的提示Hafichuk,最好的問候! –

+0

np,希望答案適合你 – hafichuk

相關問題