PHP 밖에서 출력한 HTML을 변수에 저장하기

HTML을 변수에 저장해야 할 때 따옴표로 감싸면 거부감이 든다.

$html = '<textarea id="bbp_{$context}_content" 
	class="{$editor_class}" name="bbp_{$context}_content" 
	cols="60" rows="{$textarea_rows}" 
	tabindex="{$tabindex}">{$post_content}</textarea>';

이딴 식이 돼 버리니 말이다. HTML 코드 어시스트 기능도 활용할 수 없는 경우가 많아 답답하다.

이럴 때는 ob_get_contents를 사용한다. 그러면 출력하는 내용을 그대로 받아서 변수에 저장할 수 있다.

<?php
// Start an output buffor
ob_start();
?>
출력되는 이 부분이 아래 $output에 저장된다.
<?php
// Put the output into a usable variable
$output = ob_get_contents();

// Flush the output buffer
ob_end_clean();

echo var_dump($output);
// result : string '출력되는 이 부분이 아래 $output에 저장된다.' (length=...)

핵심은 ob_start()$output = ob_get_contents(), 그리고 ob_end_clean()이다.

👇 카테고리 글 목록

대표글

댓글 남기기