The Slim Framework support forum has moved to This Tender forum is no longer maintained or monitored.

Slim3 :: Creating middleware to modify body of response

tjbett's Avatar


10 Nov, 2015 02:45 AM

I've seen examples of Slim3 performing a $response->write("Before") and $response->write("After") the next() call. This places content Before and After the body as it is being developed but doesn't modify the existing body content.

Basically, how do I capture the body content, manipulate it, and then put it back into the response object at the time of the middleware call?

Thank you

  1. 1 Posted by tjbett on 12 Nov, 2015 02:20 AM

    tjbett's Avatar

    Ok, here is what I came up with ... recommendations?

    $mw_body = function($request, $response, $next) {
        $response = $next($request, $response);

        $body = $response->getBody();

        //-- do something with $body here

        $newResp = new \Slim\Http\Response();

        return $newResp;

  2. 2 Posted by jd on 13 Nov, 2015 03:38 AM

    jd's Avatar

    Creation of new Body() object worked for me. I wanted to manipulate HTML code as a string.

    { $response = $next($request, $response);

    $str_body = (string)$response->getBody();
    $new_str_body = .... do something with the old string
    $body = new \Slim\Http\Body(fopen('php://temp', 'r+'));
    return $response->withBody($body);


Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:


Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac