Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. CsvEncoder.php

function CsvEncoder::encode

Overrides EncoderInterface::encode

File

vendor/symfony/serializer/Encoder/CsvEncoder.php, line 66

Class

CsvEncoder
Encodes CSV data.

Namespace

Symfony\Component\Serializer\Encoder

Code

public function encode(mixed $data, string $format, array $context = []) : string {
    $handle = fopen('php://temp,', 'w+');
    if (!is_iterable($data)) {
        $data = [
            [
                $data,
            ],
        ];
    }
    elseif (!$data) {
        $data = [
            [],
        ];
    }
    else {
        // Sequential arrays of arrays are considered as collections
        $i = 0;
        foreach ($data as $key => $value) {
            if ($i !== $key || !\is_array($value)) {
                $data = [
                    $data,
                ];
                break;
            }
            ++$i;
        }
    }
    [
        $delimiter,
        $enclosure,
        $escapeChar,
        $keySeparator,
        $headers,
        $escapeFormulas,
        $outputBom,
    ] = $this->getCsvOptions($context);
    foreach ($data as &$value) {
        $flattened = [];
        $this->flatten($value, $flattened, $keySeparator, '', $escapeFormulas);
        $value = $flattened;
    }
    unset($value);
    $headers = array_merge(array_values($headers), array_diff($this->extractHeaders($data), $headers));
    $endOfLine = $context[self::END_OF_LINE] ?? $this->defaultContext[self::END_OF_LINE];
    if (!($context[self::NO_HEADERS_KEY] ?? $this->defaultContext[self::NO_HEADERS_KEY])) {
        fputcsv($handle, $headers, $delimiter, $enclosure, $escapeChar);
        if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
            fwrite($handle, $endOfLine);
        }
    }
    $headers = array_fill_keys($headers, '');
    foreach ($data as $row) {
        fputcsv($handle, array_replace($headers, $row), $delimiter, $enclosure, $escapeChar);
        if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
            fwrite($handle, $endOfLine);
        }
    }
    rewind($handle);
    $value = stream_get_contents($handle);
    fclose($handle);
    if ($outputBom) {
        if (!preg_match('//u', $value)) {
            throw new UnexpectedValueException('You are trying to add a UTF-8 BOM to a non UTF-8 text.');
        }
        $value = self::UTF8_BOM . $value;
    }
    return $value;
}
RSS feed
Powered by Drupal