Search code examples
phpxmlline-breaks

how to do linebreaks in XML?


I finally got my xml-(pre-)parsing-script ready. It parses and checks each element, and saves a amount of elements to a new xml-file.

My "problem" is that in the new xml-file all is written unformatted and without linebreaks.

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++;
            }
        }

    }

How could I get my xml-slices look good, with linebreaks? .. I already tried \nbut it simply writes \n to the new file.


Solution

  • The trick is to use " instead of ' for special characters to be parsed as special.

    so

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

    should be

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

    You can also use \t for tabs, if you want indentation!