将php/mysql查询中的数据添加到XML文件中
我想添加/显示来自数据库查询的数据,并将其添加到XML文件中。 例如,我有一个表,上面有一个名字和年龄。我创建了一个mysql查询来获取它的名称和年龄。然后简单地将数据(姓名和年龄)放入一个XML文件中 你会怎么做?或者可能吗?将php/mysql查询中的数据添加到XML文件中,php,mysql,xml,wordpress,Php,Mysql,Xml,Wordpress,我想添加/显示来自数据库查询的数据,并将其添加到XML文件中。 例如,我有一个表,上面有一个名字和年龄。我创建了一个mysql查询来获取它的名称和年龄。然后简单地将数据(姓名和年龄)放入一个XML文件中 你会怎么做?或者可能吗? <?php [snip] //database code here $f = fopen('myxml.xml', 'a+'); foreach($row = mysqli_fetch_assoc($resultFromQuery)) { $str =
<?php
[snip] //database code here
$f = fopen('myxml.xml', 'a+');
foreach($row = mysqli_fetch_assoc($resultFromQuery))
{
$str = "<person>
<name>{$row['name']}</name>
<age>{$row['age']}</age>
</person>\n";
fwrite($f, $str);
}
fclose($f);
?>
假设您使用的是mysqli
,则此代码有效。如果不适合,则适合。在fopen
函数调用中,a+
告诉它在写入时打开它进行读取,并将指针放在文件的末尾
祝您好运。我建议您使用和创建XML文件
大概是这样的:
// Create XML document
$doc = new DomDocument('1.0', 'UTF-8');
// Create root node
$root = $doc->createElement('persons');
$root = $doc->appendChild($root);
while ($row = mysql_fetch_assoc($result)) {
// add node for each row
$node = $doc->createElement('person');
$node = $root->appendChild($node);
foreach ($row as $column => $value) {
$columnElement = $doc->createElement($column);
$columnElement = $node->appendChild($columnElement);
$columnValue = $doc->createTextNode($value);
$columnValue = $columnElement->appendChild($columnValue);
}
}
// Complete XML document
$doc->formatOutput = true;
$xmlContent = $doc->saveXML();
// Save to file
file_put_contents('persons.xml', $xmlContent);
你需要逃避你的价值观!