<?php
class ControllerToolXmlDownload extends Controller
{
    public function index()
    {
        $this->downloadXML('https://www.gulsumelkhatroushi.com/eticaret/api/v1/xml/856a80bffae2a24b48c49dbf75a8c4aa/aktifurunler');

        
    }

    public function downloadXML($xml_url = false, $file_name = '')
    {
        if (!$file_name)
            $file_name = @date("Ymd-His") . '.xml';

        $feed_data = array();

        if ($xml_url) {
            $feed_data['xml_url'] = $xml_url;
        }

        $xml_dir = DIR_DOWNLOAD . 'xml/';
        if (!is_dir($xml_dir)) {
            mkdir($xml_dir);
        }

        $feed_data['xml_url'] = htmlspecialchars_decode($feed_data['xml_url']);


        $save_xml_name = $xml_dir . $file_name;


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $feed_data['xml_url']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        $content = curl_exec($ch);

        if ($content == false) {
            $content = file_get_contents($feed_data['xml_url']);
        }

        $last_chars = substr($content, -1000);
        $last_tag = explode('</', $last_chars);
        $last_tag = $last_tag[count($last_tag) - 1];
        $last_tag = '</' . $last_tag;
        $content = str_replace($last_tag, "\n" . $last_tag, $content);
        file_put_contents($save_xml_name, $content);

        return $save_xml_name;
    }


}
