Skip to content
Advertisement

file_get_contents seems to add extra returns to the data

Hi I am trying to run a simple php file open, replace, and save. Here is my code:

//open file and get data
$data = file_get_contents("input.xml");

// do tag replacements or whatever you want
$data = str_replace("<Property>", "<item>", $data);
$data = str_replace("</Property>", "</item>", $data);

//save it back:
file_put_contents("output.xml", $data);

My file opens, does the replace, and saves the file. But when I opened the file I noticed that there was an extra line return after every item that previously had only one line return.

I tested printing out the data directly to my browser and noticed that the extra line breaks are being introduced in file_get_contents, not when writing back to the new file.

Anyone have any idea how to prevent these extra line returns from being introduced in the first place?

Thanks!

Advertisement

Answer

Many thanks to the commenters, that was an easier fix than I thought:

I just made the following addition:

// fix line endings 
$data = str_replace("rn", "n", $data);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement