1

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.

Leonid Glanz
  • 1,261
  • 2
  • 16
  • 36
AdmiralCrunch
  • 153
  • 12
  • Possible duplicate of [Adding a new line/break tag in XML](http://stackoverflow.com/questions/10917555/adding-a-new-line-break-tag-in-xml) – David Wilkinson Nov 20 '15 at 09:07

2 Answers2

1

Use special chars \n and \t for tabulations.

So:

fwrite($xp, "<item>\n");

fwrite($xp, "\t" . $xmlData."\n");

fwrite($xp, "</item>\n");
Anonymus
  • 163
  • 2
  • 11
1

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!

Nanne
  • 64,065
  • 16
  • 119
  • 163