Middleware influence on body

When I use middleware to remove stuff out of the generated content, my html is wierd.


public function __invoke($request, $response, $next)
	$response = $next($request, $response);
    $response->getBody()->write("change the html");
    $content = (string)$response->getBody();

    return $response;

What happens is that the first characters of my HTML are the canged ones, but the rest of the HTML is my old HTML. (I think it’s because the string length is allready set.)

I can expand the body with success, but never shrink it, which is wierd.

So I’m looking for a solution…

Hello @marcelloh

Ok let’s take this example:


$content = (string)$response->getBody();
echo $content;

The result is not "x" it’s "x234567890"!

Is this what you mean? The reason behind this is a so called stream. The rewind method just changes the offset in the stream to the first position, but it does’t clear the previous content in the stream.

To replace the whole content try this instead:

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

$stream = fopen('php://memory', 'r+');
fwrite($stream, 'new content');

return $response->withBody(new \Slim\Http\Stream($stream));

I changed this into your proposol, and it works. (never noticed it was a stream)
:smile: Thanks