Adding PHP/HTML code inside page from custom template

This is how to code the shortcode

function foobar_func( $atts ){
    return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

And to execute a function using output buffering

add_shortcode( 'shortcode_tag', 'function_name' );
function function_name($atts) {
    ob_start();

    // Add your code

    $var = ob_get_contents();
    ob_end_clean();
    return $var;

}