2010-12-01 141 views
0

我需要从我的php代码创建xml文件的帮助。我创建了一个函数,它根据需要形成xml,但我不知道如何将文件中形成的xml保存。从php创建xml文件的问题

此外,如果你还可以告诉我,下次如何更新已经创建的XML文件。

我的代码看起来像下面:

public function create_xml() 
{ 
    $output = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> "; 
    $output .= "<data>"; 
    $output .= "<news>"; 
    $news_articles = new C7_News(); 
    $db = C7_Bootstrap::getDb(); 
    $foxsport_sql = "SELECT headline, link FROM c7_news 
         WHERE source = 'foxsports' AND category = 'Breaking News' 
         LIMIT 0,4"; 
    $foxsport_rowset = $db->fetchAll($foxsport_sql); 
    $data = array(); 
    foreach($foxsport_rowset as $foxsport_row) 
    { 
     $output .= "<title>"; 
     $output .= "<description>"; 
     $output .= "<![CDATA["; 
     $output .= $foxsport_row['headline']; 
     $output .= "]]>"; 
     $output .= "<link>"; 
     $output .= $foxsport_row['link']; 
     $output .= "</link>"; 
     $output .= "</title>"; 
    } 
    $output .= "</news>"; 
    $output .= "</data>"; 

} 

我可能会做错事太多,PLZ让我知道创建XML的最好方法。

谢谢 Zeeshan

回答

2

我会在这里添加更多信息。

此外,如果你还可以告诉我,下次如何更新已经创建的XML文件。

如果要在解析XML 更新,在SimpleXml extension提供易用的API 解析写作XML文件。

我也可能做错了,请让我知道创建XML的最佳方式。

有很多方法可以做到这一点,但我更喜欢使用PHP “模板引擎”写HTML时XML(或任何* ML这个问题)。

<?php echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?> " ?> 
    <?php 
     $news_articles = new C7_News(); 
     $db = C7_Bootstrap::getDb(); 
     $foxsport_sql = "SELECT headline, link FROM c7_news 
        WHERE source = 'foxsports' AND category = 'Breaking News' 
        LIMIT 0,4"; 
     $foxsport_rowset = $db->fetchAll($foxsport_sql); 
    ?> 
    <data> 
     <news> 
     <?php foreach($foxsport_rowset as $foxsport_row): 
     <title> 
      <description> 
      <![CDATA[ 
      <?php echo $foxsport_row['headline'] ?> 
      ]]> 
      </description> 
      <link><?php echo $foxsport_row['link']</link> 
     </title> 
     <?php endforeach; ?> 
     </news> 
    </data> 

这将输出的XML 是一个更容易阅读

但我不知道如何保存的XML文件中的。

至于如何将这些保存到一个文件,你应该有另一个PHP文件include这个“模板”(假设该模板被称为xml_template.php):

ob_start(); 
    include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'xml_template.php'; 
    $output = ob_get_clean(); 

然后你再有XML字符串上的$output变量,可以做的弗拉德注意到。P

// If file is missing, it will create it. 
    $file = fopen("file.xml", "w"); 
    fwrite($file, $output); 
    fclose($file); 
0

在你的函数的末尾添加这一点。

// If file is missing, it will create it. 
$file = fopen("file.xml", "w"); 
fwrite($file, $output); 
fclose($file); 
0

使用

file_put_contents($file, $output); 

你可能想在参数传递的文件的路径:

$stream->create_xml($file); 

或原因,应该通过其他方法来处理/类,例如

$stream->create_xml(); 
$stream->save_xml($file);