To CSV conversion

@param   mixed   $data
@param   mixed   $delimiter
@param   mixed   $enclose_numbers
@param   array   $headings  Custom headings to use
@return  string
170852
public function to_csv($data = null, $delimiter = null, $enclose_numbers = null, array $headings = array())
	{
		// csv format settings
		$newline = \Config::get('format.csv.newline', \Config::get('format.csv.export.newline', "\n"));
		$delimiter or $delimiter = \Config::get('format.csv.delimiter', \Config::get('format.csv.export.delimiter', ','));
		$enclosure = \Config::get('format.csv.enclosure', \Config::get('format.csv.export.enclosure', '"'));
		$escape = \Config::get('format.csv.escape', \Config::get('format.csv.export.escape', '\\'));
		is_null($enclose_numbers) and $enclose_numbers = \Config::get('format.csv.delimit_numbers',  true);

		// escape, delimit and enclose function
		$escaper = function($items, $enclose_numbers) use($enclosure, $escape, $delimiter) {
			return 	implode($delimiter, array_map(function($item) use($enclosure, $escape, $delimiter, $enclose_numbers) {
				if ( ! is_numeric($item) or $enclose_numbers)
				{
					$item = $enclosure.str_replace($enclosure, $escape.$enclosure, $item).$enclosure;
				}
				return $item;
			}, $items));
		};

		if ($data === null)
		{
			$data = $this->_data;
		}

		if (is_object($data) and ! $data instanceof \Iterator)
		{
			$data = $this->to_array($data);
		}

		// Multi-dimensional array
		if (empty($headings))
		{
			if (is_array($data) and \Arr::is_multi($data))
			{
				$data = array_values($data);

				if (\Arr::is_assoc($data[0]))
				{
					$headings = array_keys($data[0]);
				}
				else
				{
					$headings = array_shift($data);
				}
			}
			// Single array
			else
			{
				$headings = array_keys((array) $data);
				$data = array($data);
			}
		}

		$output = $escaper($headings, true).$newline;

		foreach ($data as $row)
		{
			$output .= $escaper($row, $enclose_numbers).$newline;
		}

		return rtrim($output, $newline);
	}
291800
public static function encode($data, String $key = NULL, String $separator = NULL) : String
    {
        if( ! is_scalar($data) )
        {
            $data = (array) $data;
        }
        
        $word      = NULL;
        $key       = $key       ?: self::$key;
        $separator = $separator ?: self::$separator;
 
        foreach( $data as $k => $v )
        {
            $word .= self::_security($k).$key.self::_security($v).$separator;
        }

        return mb_substr($word, 0, -(mb_strlen($separator)));
    }
1356336
public function setCsv(array &$data, $detectHead = true)
    {
        $handle     = self::createMemoryHandle();
        if($detectHead && count($data)> 0){
            fputcsv($handle, array_keys($data[0]), $this->delimiter, $this->enclosure);
        }
        foreach ($data as $row) {
            fputcsv($handle, $row, $this->delimiter, $this->enclosure);
        }
        rewind($handle);
        $output = chr(255) . chr(254
            ) . mb_convert_encoding('sep=' . $this->delimiter . "\n" . stream_get_contents($handle),
                self::UTF_16_LE,
                $this->encodingFrom
            );
        $this->setData($output);
        fclose($handle);
    }
1298794
public function encode($data, $inline = 2, $indent = 4, $flags = 0): string
    {
        try {
            $flags |= \Symfony\Component\Yaml\Yaml::DUMP_OBJECT;
            return \Symfony\Component\Yaml\Yaml::dump($data, $inline, $indent, $flags);
        } catch (\Throwable $e) {
            throw new EncodeException($e->getMessage(), $e->getCode(), $e);
        }
    }
315076
public function encode($data, $leaveEOD = false)
    {
        $t = \unpack('H*', $data);
        return \current($t)
            . ($leaveEOD ? '' : '>');
    }
1013540
public function encodeMulticall($data) {

        $packed_requests = array();

        foreach ( $data as $methodName => $params ) {

            if ( is_int($methodName) && count($params) == 2 ) {

                array_push($packed_requests, array(
                    "methodName"    =>  $params[0],
                    "params"        =>  $params[1]
                ));    

            } else {

                array_push($packed_requests, array(
                    "methodName"    =>  $methodName,
                    "params"        =>  $params
                ));

            }

        }

        return $this->encodeCall("system.multicall", array($packed_requests));

    }
532540
public function exportCsv($filename, $data, $options = array())
    {
        $config = $this->getConfig();
        $options = array_merge($config, $options);

        if (!$this->_trigger('beforeExportCsv', array($filename, $data, $options))) {
            return false;
        }

        // open the file
        if ($file = fopen($filename, 'w')) {
            // Add BOM for proper display UTF-8 in EXCEL
            if($options['excel_bom']) {
                fputs($file, chr(239) . chr(187) . chr(191));
            }
            // Iterate through and format data
            $firstRecord = true;
            foreach ($data as $record) {
                $record = $record->toArray();
                $row = array();
                foreach ($record as $field => $value) {
                    if ( !is_array($value) ) {
                        $row[] = $value;
                        if ($firstRecord) {
                            $headers[] = $field;
                        }
                        continue;
                    }
                    $table = $field;
                    $fields = $value;
                    // TODO add parsing for HABTM
                    foreach ($fields as $field => $value) {
                        if (!is_array($value)) {
                            if ($firstRecord) {
                                $headers[] = $table . '.' . $field;
                            }
                            $row[] = $value;
                        } // TODO due to HABTM potentially being huge, creating an else might not be plausible
                    }
                }
                $rows[] = $row;
                $firstRecord = false;
            }

            if ($options['headers']) {
                // write the 1st row as headings
                fputcsv($file, $headers, $options['delimiter'], $options['enclosure']);
            }
            // Row counter
            $r = 0;
            foreach ($rows as $row) {
                fputcsv($file, $row, $options['delimiter'], $options['enclosure']);
                $r++;
            }

            // close the file
            fclose($file);

            $this->_trigger('afterExportCsv', array());

            return $r;
        } else {
            return false;
        }
    }
114498
public function save(array $headers, array $data)
    {
        $output = $contents = [];

        $enclosure = $this->getCsvEnclosure();
        $delimiter = $this->getCsvDelimiter();

        $contents[] = $enclosure
            . implode($enclosure . $delimiter . $enclosure, $headers)
            . $enclosure;

        if (!empty($data)) {
            foreach ($data as $item) {
                foreach ($item as $line) {
                    foreach ($headers as $index => $value) {
                        if (isset($line[$value]) && $line[$value] !== '') {
                            $output[$value] = $enclosure . (string)$line[$value] . $enclosure;
                            unset($line[$value]);
                        } else {
                            $output[$value] = '';
                        }
                    }
                    $contents[] = implode($delimiter, array_merge($output, $line));
                }
            }
        }

        $filePath = $this->getFilePath();

        if (file_put_contents($filePath, chr(239) . chr(187) . chr(191) . implode("\n", $contents))) {
            return $filePath;
        }

        return '';
    }
349053
public function tocsv($collection, $fileName = null, $delimiter = ';')
    {
        s()->async(true);

        ini_set('memory_limit', '2048M');

        // Set passed file name or generate it
        $fileName = $fileName ?: 'Export' . date('dmY') . '.csv';

        // Output file from browser
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $fileName);
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');

        // Write to php temp because php natively support csv files creation
        $handle = fopen('php://temp', 'r+');
        //fputs($handle, chr(0xEF) . chr(0xBB) . chr(0xBF)); // UTF-8 BOM
        foreach ($collection->toArray() as $line) {
            fputcsv($handle, $line, $delimiter);
        }

        // Read file from temp
        rewind($handle);
        $csv = '';
        while (!feof($handle)) {
            $csv .= fread($handle, 8192);
        }
        fclose($handle);

        // Convert to Excel readable format
        echo mb_convert_encoding($csv, 'Windows-1251', 'UTF-8');
    }
454220
protected function getFormattedRow($rowData, $columnLengths, $header = false) {
        $response = $this->getChar('left');

        foreach ($rowData as $key => $field) {
            if ($header) {
                $color = $this->getHeaderColor();
            } else {
                $color = $this->fields[$key]['color'];
            }

            $fieldLength  = mb_strwidth($field) + 1;
            $field        = ' '.($this->getUseColors() ? $this->getColorFromName($color) : '').$field;
            $response    .= $field;

            for ($x = $fieldLength; $x < ($columnLengths[$key] + 2); $x++) {
                $response .= ' ';
            }
            $response .= $this->getChar('middle');
        }

        $response = substr($response, 0, strlen($response) - 3) . $this->getChar('right') . PHP_EOL;
        return $response;
    }
992468
public function str_getcsv( $line, $delimiter = ',', $enclosure = '"', $escape = '\\' ) {

		$line = str_replace( "\r\n", "\n", $line );
		$line = str_replace( "\r", "\n", $line );

		if ( '\n' !== $delimiter && function_exists( 'str_getcsv' ) ) {
			return str_getcsv( $line, $delimiter, $enclosure, $escape );
		}

		$delimiter = str_replace( '/', '\/', $delimiter );
		$enclosure = preg_quote( $enclosure, '/' );

		$split = "/{$delimiter}(?=(?:[^{$enclosure}]*{$enclosure}[^{$enclosure}]*{$enclosure})*(?![^{$enclosure}]*{$enclosure}))/";

		$data = preg_split( $split, trim( $line ), - 1, PREG_SPLIT_NO_EMPTY );

		if ( '\n' !== $delimiter ) {
			$data = preg_replace( "/^{$enclosure}(.*){$enclosure}$/s", '$1', $data );
		}

		return $data;
	}
776101
public static function csvFileToArray($filename='', $delimiter=',')
    {
        $header = null;
        $data = [];
        if (($handle = fopen($filename, 'r')) !== false) {
            while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) {
                if (!$header) {
                    $header = $row;
                } else {
                    $data[] = array_combine($header, $row);
                }
            }
            fclose($handle);
        }

        return $data;
    }
777918
private function dataToJson($data)
        {
            $cols = $this->getColumns($data);

            $rows = [];

            foreach ($data as $key => $row) {
                if ($key != 0 || !$this->_skipFirstRow) {
                    $c = [];

                    foreach ($row as $v) {
                        $c[] = ['v' => $v];
                    }

                    $rows[] = ['c' => $c];
                }
            }

            return json_encode(['cols' => $cols, 'rows' => $rows]);
        }
69767
public function csv_to_php( $data, $delimiter = ',' ) {

		pods_deprecated( "PodsAPI->csv_to_php", '2.3.5' );

		$data = pods_migrate( 'sv', $delimiter, $data )->parse();

		return $data['items'];
	}
632425
function encode($data): string {
        $msg = \json_encode($data);
        if($msg === false && \json_last_error() !== \JSON_ERROR_NONE) {
            throw new \CharlotteDunois\Yasmin\WebSocket\DiscordGatewayException('The JSON encoder was unable to encode the data. Error: '.\json_last_error_msg());
        }
        
        return $msg;
    }
1225164
public function write( $data, $headers = array() )
	{
		$output = array();
		if( $headers )
		{
			$output[] = implode( $this->separator, $headers );
		}
		foreach( $data as $line )
		{
			foreach( $line as $nr => $value )														//  iterate line values
				if( substr_count( $value, $this->separator ) > 0 )									//  separator found in value
					if( substr( $value, 0, 1 ).substr( $value, -1 ) != '""' )						//  value is not masked
						$line[$nr]	= '"'.addslashes( $value ).'"';									//  mask value
			$line = implode( $this->separator, $line );
			$output[] = $line;
		}
		$file	= new FS_File_Writer( $this->fileName );
		return $file->writeArray( $output );
	}
454822
function parseResponse($headers, $data)
    {
        $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' headers:');
        $this->appendDebug($this->varDump($headers));
        if (!isset($headers['content-type'])) {
            $this->setError('Response not of type text/xml (no content-type header)');

            return FALSE;
        }
        if (!strstr($headers['content-type'], 'text/xml')) {
            $this->setError('Response not of type text/xml: ' . $headers['content-type']);

            return FALSE;
        }
        if (strpos($headers['content-type'], '=')) {
            $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1));
            $this->debug('Got response encoding: ' . $enc);
            if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i', $enc)) {
                $this->xml_encoding = strtoupper($enc);
            } else {
                $this->xml_encoding = 'US-ASCII';
            }
        } else {
            // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
            $this->xml_encoding = 'ISO-8859-1';
        }
        $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser');
        $parser = new nusoap_parser($data, $this->xml_encoding, $this->operations, $this->decode_utf8);
        // add parser debug data to our debug
        $this->appendDebug($parser->getDebug());
        // if parse errors
        if ($errstr = $parser->getError()) {
            $this->setError($errstr);
            // destroy the parser object
            unset($parser);

            return FALSE;
        } else {
            // get SOAP headers
            $this->responseHeaders = $parser->getHeaders();
            // get SOAP headers
            $this->responseHeader = $parser->get_soapheader();
            // get decoded message
            $return = $parser->get_soapbody();
            // add document for doclit support
            $this->document = $parser->document;
            // destroy the parser object
            unset($parser);

            // return decode message
            return $return;
        }
    }