I'm trying to make sure I only pull information from an external resource when it's not already there, and therefore I'm trying to write the result to a file if the file isn't already there. I use the following code: if (file_exists($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json')) { $get_holidays_year_and_month = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json', true); } else { $write_to_file = json_decode(file_get_contents('http://holidayapi.com/v1/holidays?country=NO&year='.$request_year.'&pretty')); file_put_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json',$write_to_file); $get_holidays_year_and_month = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json',true); } PHP: It works, apart from the fact that it doesn't write anything to the file - it creates the file, but the file is empty, and I'm wondering if that's because it returns a stdObject - if that's it, how do I create something I can put into the file? No errors returned, nothing says it doesn't work, but for some reason, there's nothing in the file after it gets written. If I var_dump() the $write_to_file variable before the file_put_contents(), it contains the expected result.
And, of course, right after I post it here, I get an epiphany, and remember what I've forgotten. Here's working code: if (file_exists($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json')) { $get_holidays_year_and_month = unserialize(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json', true)); } else { $write_to_file = json_decode(file_get_contents('http://holidayapi.com/v1/holidays?country=NO&year='.$request_year.'&pretty')); file_put_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json',serialize($write_to_file)); $get_holidays_year_and_month = unserialize(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json',true)); } PHP: serialize() and unserialize(), if you can't see the difference.
Yes, such things happen)) It's useful sometimes to take a break and the decision of the problem appears by itself) and let me give you just a little advice - I think that way will be little better if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json')) { $write_to_file = json_decode(file_get_contents('http://holidayapi.com/v1/holidays?country=NO&year='.$request_year.'&pretty')); file_put_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json',serialize($write_to_file)); } $get_holidays_year_and_month = unserialize(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/utilities/holidays_'.$file_date.'.json', true)); PHP: