echoing the contents of
$data – I guess thats also what you are seeing if I understood that correctly.
If the code is included in your
functions.php like this, it probably gets executed as soon as the
functions.php file is loaded, which might be too late or too early.
To be able to control when the code executes, you should have a look into WordPress Hooks and hook your code into this mechanism.
If you can tell me more about what exactly you are trying to do, I might be able to give a more detailed answer.
Just as a sidenote: Take care not to cross over into Plugin territory with your theme. As soon as you are trying to do anything more than modifying the look of something, it doesn't belong into
functions.php anymore but a separate plugin.