Pergunta

Olá, eu tenho um script que cria um arquivo e o armazena no servidor. O arquivo é codificado no UTF-8 e é um tipo de arquivo XML para o software CMAP.

Se eu abrir o arquivo diretamente do servidor, não há problema e o arquivo poderá ser lido.

Estou forçando um download desse arquivo quando um usuário vai para um URL específico. Após esse download, o arquivo é ilegível pelo software CMAP. Eu tenho que entrar no meu editor de texto (bloco de notas ++) e alterar a codificação de UTF-8 para UTF-8 sem BOM.

Estou enviando os cabeçalhos errados? O PHP está fazendo algo com o arquivo quando está baixando?

Qualquer conselho sobre isso seria realmente apreciado.

Saúde Drew

EDITAR

Desculpe, há muito código envolvido em algumas classes diferentes. Incluí o código que estou usando para enviar o arquivo para o navegador:

function exportCMAP()
{   
    $serializer = new Serializer();
    $serializer->serializeCmap();

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=export.cxl");
    header("Content-Type: x-cmap/text-xml");
    header("Content-Transfer-Encoding: binary");

    readfile("temp/export.cxl");
}

Se o código que gerar o XML (usando XMLWriter) for necessário, eu também posso postar isso.

EDITAR

Conforme solicitado aqui é o código em que o XML está sendo produzido - está em outra classe:

        function serializeCmap()
    {

        $storeManager = new StoreManager();         
        $linkedNodes = $storeManager->getLinkedNodes();

        $namespaces = Array();

        $writer = new XMLWriter();

        $writer->openMemory();
        $writer->setIndent(4); 

        $writer->startDocument('1.0', 'utf-8');

            $writer->startElement('cmap');

                $writer->writeAttribute('xmlns', 'http://cmap.ihmc.us/xml/cmap/');
                $writer->writeAttribute('dc', 'http://purl.org/dc/elements/1.1/');

            $writer->startElement('res-meta');

                $writer->writeElement("dc:title", "Full schema for Cmap");
                $writer->writeElement("dc:description", "Description Goes Here");

            $writer->endElement();  

            $writer->startElement('map');

                $writer->startElement('concept-list');

                    foreach($linkedNodes['nodes'] as $node=>$id) {

                        $writer->startElement('concept');

                            $writer->writeAttribute("id", $id);
                            $writer->writeAttribute("label", $node);

                        $writer->endElement();
                    }

                $writer->endElement();

                $writer->startElement('linking-phrase-list');

                    foreach($linkedNodes['phrases'] as $phrase=>$id) {

                        $writer->startElement('linking-phrase');

                            $writer->writeAttribute("id", $id);
                            $writer->writeAttribute("label", $phrase);

                        $writer->endElement();
                    }

                $writer->endElement();

                $writer->startElement('connection-list');

                    foreach($linkedNodes['connections'] as $key=>$val) {

                        $writer->startElement('connection');

                            $writer->writeAttribute("from-id", $val['from']);
                            $writer->writeAttribute("to-id", $val['phrase']);

                        $writer->endElement();

                        $writer->startElement('connection');

                            $writer->writeAttribute("from-id", $val['phrase']);
                            $writer->writeAttribute("to-id", $val['to']);

                        $writer->endElement();
                    }

                $writer->endElement();

            $writer->endElement();

        $writer->endElement();

        $writer->endDocument();

        file_put_contents("temp/export.cxl",$writer->outputMemory());
    }
Foi útil?

Solução

Você deve adicionar duas coisas importantes:

  1. Teste se o cabeçalho HTTP ainda não foi enviado e
  2. verifique se não há mais saída do que o de readfile.

Então tente isto:

function exportCMAP() {
    if (headers_sent()) {
        // HTTP header has already been sent
        return false;
    }
    // clean buffer(s)
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=export.cxl");
    header("Content-Type: x-cmap/text-xml");
    header("Content-Transfer-Encoding: binary");
    readfile("temp/export.cxl");
    // avoid any further output
    exit;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top