I am learning to create web pages using PHP. I have some PHP files that mix html tags and PHP code to construct dynamic html pages. In order to better learn and understand how PHP works, I would like to be able see the exact output text that is generated from the PHP interpreter.
The problem is, I don’t know how to view that.
If I use a browser, it takes the output and formats it according to HTML tags.
If I use the "display source" option of my browser (for example "Developer tools" in Chrome), the source code is displayed already formatted in a certain way (indents, line breaks, etc. – I looked in the Chrome settings but changing the preferences did not seem to have any impact)
So how can I display the RAW output text without any formatting?
Thank you
2
Answers
I had the same problem, when I started using PHP inside of HTML.
The first solution that comes into my mind is to use PHP echo to see the exact output text that is generated from the PHP interpreter.
Use this echo php language construct inside of almost any html tag (p, h1, span or any other html tag) and the browser will output the text for you.
Other way is to print it out as a javascript alert like this:
If you use this other way, the result will pop out for you as a javascript alert. Be careful with using ‘ and " or your code will crash.
Also, keep in mind that this way you can output only strings or numbers! If you create a PHP object, it cannot be printed this way. You will have to turn it into a string somehow.
Assuming that you essentially want to see the output, not the filtered output generated by the browser. There are three ways you can do it:
1 curl
If you are happy with console commands the easiest way is to use a tool like curl:
you can then open the file
myrawpage.html
in your favourite text editor.2 change the content-type header
If you change the
content-type
header totext/plain
your browser should ignore the html formatting and display the page – this may not work for all browsers, and you will have to change it back to view your page – not recommended.3 create a helper php page
This is sort of a mashup of the two above: if you create a page like this:
(inspired by How to fetch a webpage with php curl and display that webpage html? )
You will be able to see the raw source in your browser by calling this script, and still access the original page. DON’T PUBLISH THIS PAGE keep it in a sub-folder which you exclude from any upload or CI/CD script
note
"View page source" in your browser ought to show you the raw code. As opposed to that, if you press F12 and look at the source, that is the parsed source, which is representing the DOM as manipulated by any Javascript, etc.