2012-04-30 89 views
-1
//this is the code that creates the array and the output follows 
while ($results_row = mysql_fetch_assoc($results)) { 
     $returned_results[]= array(
            'partName'=>$results_row['partName'], 
            'description'=>$results_row['description'], 
            'price'=>$results_row['price'] 

//what is contained in the array is as follows 
Array 
(
[partName] => Cooler Master CM Storm Trooper Case 
[description] => Armored appearance. Nicely placed handle at the top. At the front; ext 
[price] => 36000 
) 
1 

Array 
(
[partName] => Cooler Master eXtreme Power Plus 500-Watt 
[description] => Power Plus 500-Watt Power Supply,many SATA and peripheral connectors. 
[price] => 23000 
) 
1 

Array 
(
[partName] => Coolmax M-500B ATX Power Supply 
[description] => The Coolmax M-500B ATX Power Supply has 5 SATA and 5 Peripheral, 8 pin 
[price] => 20000 
) 

我需要将包含在数组变量($ returned_results [])中的数据写入xml文件。之后,我会在xml表格中显示它。但我想我可以管理后者。你能帮我看一个代码示例吗?请&谢谢!将数组写入xml文件

XML文件中应conatin看起来像这样

<?xml version="1.0" encoding="utf-8"?> 
    <results> 
      <partName>Cooler Master CM Storm Trooper Case</partName> 
      <description>Armored appearance. Nicely placed handle at the top. At the front; ext... </description> 
      <price>36000</price> 
    </results> 
    <results> 
      <partName>Cooler Master eXtreme Power Plus 500-Watt</partName> 
      <description>Power Plus 500-Watt Power Supply,many SATA and peripheral connectors. ... </description> 
      <price>23000</price> 
    </results 
    <results> 
      <partName>Coolmax M-500B ATX Power Supply </partName> 
      <description>The Coolmax M-500B ATX Power Supply has 5 SATA and 5 Peripheral, 8 pin..</description> 
      <price>20000</price> 
    </results> 
+0

[Stack Overflow是不是你个人的研究助理(http://meta.stackexchange.com/a/128553/155197) – PeeHaa

回答

0

你可以使用PHP本身(而不是echofwrite等)来编写XML。

ob_start(); 
?> 
<?xml version="1.0" encoding="utf-8"?> 
<?php 
while ($results_row = mysql_fetch_assoc($results)) { 
?> 
<results> 
    <partName><?php echo htmlspecialchars($results_row['partName']);?></partName> 
</results> 
<?php 
} 

file_put_contents('file.xml', ob_get_clean()); 
+0

O.K,那么我在标记上收到错误消息。它告诉我元素“结果”在这种情况下不允许作为子元素体。我该如何解决这个问题 – Fadamie

+0

这是PHP领域之外的问题:) –

+0

这是因为只能有一个根节点......这里所有''节点都被追加到根节点。 –

0

使用fwrite()将数组数据。例如:

$filecontents = file_get_contents ("file.xml"); 
$file = fopen(file.xml, w+); 
//If you uncomment the next line, it will keep the current contents, if not it will overwrite it 
//fwrite($file, $filecontents); 
fwrite($file, $string/array-to-write); 
fclose($file); 
+0

对不起,如果我不清楚。它更多的是用我以上指定的特定格式写入文件.. – Fadamie

+0

使用foreach循环? –

+0

是的,你能否举个例子。 – Fadamie