【问题标题】:how to do linebreaks in XML?如何在 XML 中进行换行?
【发布时间】:2015-11-20 09:02:37
【问题描述】:

我终于准备好了我的 xml-(pre-)parsing-script。它解析和检查每个元素,并将一定数量的元素保存到一个新的 xml 文件中。

我的“问题”是在新的 xml 文件中,所有内容都是未格式化且没有换行符的。

while ($xml = $chunk->read()) {
    $obj = simplexml_load_string($xml);

    // check if ID is in Array
    if(!in_array((string)$obj->id, $ids)) {
        $chunkCount++;

        $xmlData .= '<product>';
        foreach($obj as $key => $value) {
            $xmlData .= '<'.$key.'>'.$value.'</'.$key.'>';
            }
        $xmlData .= '</product>\n';

        // if $chunkLimit is reached, save to file
        if($chunkCount == $chunkLimit) {            
            $xp = fopen($file = "slices/slice_".$sliceCount.".xml", "w");
            fwrite($xp, '<?xml version="1.0" ?>'."");
            fwrite($xp, "<item>");
            fwrite($xp, $xmlData);
            fwrite($xp, "</item>");
            fclose($xp);
            print "Written ".$file."<br>";

            $xmlData = '';
            $chunkCount = 0;
            $sliceCount++;
            }
        }

    }

如何让我的 xml-slices 看起来不错,带有换行符? .. 我已经尝试过\n,但它只是将\n 写入新文件。

【问题讨论】:

标签: php xml line-breaks


【解决方案1】:

诀窍是使用" 而不是' 将特殊字符解析为特殊字符。

所以

$xmlData .= '</product>\n';

应该是

$xmlData .= "</product>\n";

如果你想要缩进,你也可以使用\t 来表示标签!

【讨论】:

    【解决方案2】:

    在表格中使用特殊字符 \n 和 \t。

    所以:

    fwrite($xp, "<item>\n");
    
    fwrite($xp, "\t" . $xmlData."\n");
    
    fwrite($xp, "</item>\n");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-26
      • 2010-09-08
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多