0

PHP function \http_parse_headers() parses HTTP headers into an associative array.

But is there some reverse function? Which parses associative array into HTTP headers?

Cannot find anything :(

(it's for saveing email into textual .eml file)

1
  • 3
    No, there isn't. But it's so trivial to create one on your own, don't you think? Commented Apr 11, 2017 at 7:56

1 Answer 1

1

There isn't a function that turns associative array into text-representation of headers. The reason: this function is extremely trivial to create.

Headers are defined as key: value delimiter is \r\n. There is another \r\n delimiter between headers and body.

Lets take an example array:

$headers = [
    'Content-Length': 50,
    'Content-Encoding': 'gzip'
];

The goal: provide a string that represents HTTP headers

function parse_array_to_headers(array $headers)
{
    $result = [];
    $delimiter = "\r\n";

    foreach($headers as $name => $value)
    {
        $result[] = sprintf("%s: %s", $name, $value);
    }

    return implode($delimiter, $result);
}

Note: this function will not check the validity of array and it won't return the string with two repetitions of \r\n at the end. This example serves to show how easy it should be to add missing function. Adjust according to your needs. Also, I didn't test this so don't copy paste it! :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.