使用php将字符串的第一个字符大写.然后用XMLWriter输出


Capitalize first character of string using php. Then output with XMLWriter.

这可能真的很简单,但我不知道最好的方法。我用php从mysqli数据库中提取数据以创建XML文档。我的代码下面的工作,但在标题字段的数据是所有的大写。我只需要第一个字母大写,其余字母小写。我知道我需要ucwords功能,但还不行。Title字段有多个全大写的单词。

在进入XML区域之前,我需要用ucwords格式化数据。我更喜欢在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);
 }
?>

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的主要原因是,如果将来对数据库进行模式更改,则不能保证数据库列的顺序相同。

祝你好运!