Skip to content
Richard edited this page Feb 27, 2016 · 1 revision

HTTP Headers

Transphporm supports setting HTTP Headers. You must target an element on the page such as HTML and you can use the :header pseudo element to set a HTTP header. For example a redirect can be done like this:

html:header[location] {content: "/redirect-url"; }

Transphporm does not directly write HTTP headers. The return value of the output() function is an array consisting of a body and headers. body is the rendered HTML code and headers contains any HTTP headers which have been set.

$xml = '<html><div>Foo</div></html>';
$tss = 'html:header[location] {content: "/redirect-url"; }';

$template = new \Transphporm\Builder($xml, $tss);

print_r($template->output());

Will print:

Array (
	'body' => '<html><div>foo</div></html>',
	'headers' => Array (
		Array (
			[0] => 'location',
			[1] => '/redirect-url'
		) 



	)
	
)

To actually send the headers to the browser you need to manually call the header command:

foreach ($template->output()->headers as $header) {
	header($header[0] . ': ' . $header[1]);
}

Conditionally applying HTTP headers

In most cases, you will want to conditionally display a header. For example:

  • Redirect on success.
  • Send a 404 header when a record could not be found.

To do this, you can use conditional data lookups:

class Model {
	public function getProduct() {
		return false;
	}
}



$tss = 'html:data[getProduct='']:header[status] {content: '404'}

$xml = '<html></html>';

$data = new Model;

$template = new \Transphporm\Builder($xml, $tss);

$output = $template->output($data);

print_r($output->headers)

Prints:

Array (
	[0] => 'status',
	[1] => '404'

)

To use this, you should then call the inbuilt php http_response_code function with this status:

foreach ($template->output()->headers as $header) {
	if ($header[0] === 'status') http_response_code($header[1]);
	else header($header[0] . ': ' . $header[1]);
}

Transphporm does not send any headers

Transphporm does not send any output to the browser by default. This is for maximum flexibility. You still must manually send the headers and echo the body.