【问题标题】:output or write to a xml file?输出或写入xml文件?
【发布时间】:2010-12-15 02:32:03
【问题描述】:
$fp = fopen('data.txt', 'r');

$xml = new SimpleXMLElement('<allproperty></allproperty>');

while ($line = fgetcsv($fp)) {
   if (count($line) < 4) continue; // skip lines that aren't full

   $node = $xml->addChild('aproperty');
   $node->addChild('postcode', $line[0]);
   $node->addChild('price', $line[1]);
   $node->addChild('imagefilename', $line[2]);
   $node->addChild('visits', $line[3]);
}

echo $xml->saveXML();

我正在使用这个脚本将文本文件转换为 xml 文件,但我想将它输出到一个文件中,我该如何做这个 simpleXML,干杯

【问题讨论】:

    标签: php xml simplexml xmlwriter


    【解决方案1】:

    file_put_contents 函数可以做到这一点。该函数采用文件名和一些内容并将其保存到文件中。

    因此,重拾您的示例,您只需将 echo 语句替换为 file_put_contents

    $xml = new SimpleXMLElement('<allproperty></allproperty>');
    $fp = fopen('data.txt', 'r');
    
    while ($line = fgetcsv($fp)) {
       if (count($line) < 4) continue; // skip lines that aren't full
    
       $node = $xml->addChild('aproperty');
       $node->addChild('postcode', $line[0]);
       $node->addChild('price', $line[1]);
       $node->addChild('imagefilename', $line[2]);
       $node->addChild('visits', $line[3]);
    }
    
    file_put_contents('data_out.xml',$xml->saveXML());
    

    【讨论】:

      【解决方案2】:

      作为记录,您可以使用 asXML() 。我的意思是,它是right there in the manual,只要阅读它,你的生活就会变得更轻松。 (我认为,也许向 StackOverflow 询问基本的东西对某些人来说更容易)

      另外,这个更具间接性,您不一定需要为每个孩子使用addChild()。如果没有该名称的子项,则可以使用对象属性表示法直接分配:

      $fp = fopen('data.txt', 'r');
      
      $xml = new SimpleXMLElement('<allproperty />');
      
      while ($line = fgetcsv($fp)) {
         if (count($line) < 4) continue; // skip lines that aren't full
      
         $node = $xml->addChild('aproperty');
         $node->postcode      = $line[0];
         $node->price         = $line[1];
         $node->imagefilename = $line[2];
         $node->visits        = $line[3];
      }
      
      $xml->asXML('data.xml');
      

      【讨论】:

      • 使用$xml->asXML('data.xml')的问题;是当您的 xml 格式错误时,例如,如果您通过 curl 从远程 Api 接收 xml 并尝试保存它。它不会保存并给你错误 cannot use asXML on Boolean
      猜你喜欢
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 2016-07-13
      • 2016-02-25
      • 2011-11-25
      • 2017-06-03
      相关资源
      最近更新 更多