views:

93

answers:

3

This will not validate because of the output from print_r, is it not supposed to be used "on a site" or do one have to format it in a certain way?

  <?php
   $stuff1 = $_POST["stuff1"];//catch variables
   $stuff2 = $_POST["stuff2"]; 
   $stuff3 = $_POST["stuff3"]; 
   $myStuff[0] = $stuff1;//put into array
   $myStuff[1] = $stuff2;
   $myStuff[2] = $stuff3;

   print_r($myStuff);

  ?>
+4  A: 

print_r() is mainly designed as a helpful tool for developers, not for actual production use in a manner that end-users would see. Thus, you shouldn't really be trying to validate it - if you're at the stage where you're trying to get stuff to validate, you shouldn't be using print_r anyway.

Amber
Ok it is just a tool in the development process?
Chris_45
That's what he said, yes.
Filip Ekberg
+1  A: 

A plain print_r outputs text, so there's no reason for it not to affect validation. To print it out nicely formatted on an HTML page, use a <pre>:

$printout = print_r($my_var);
echo "<pre>$printout</pre>";

If you don't want to display it, but only to see it as a developer, place it in an HTML (<!-- any text -->).

Max Shawabkeh
Plain text may not appear in every HTML element, so it *can* affect validation. Judging by the comment below the question, this is the OPs problem.
Gordon
+2  A: 

The validator can't distinguish the output of print_\r() from the surrounding html structure; it simply parses the whole character stream. If the output of your print_r() contains characters that have a special meaning in html (apparently < and > in your case) the validator must assume that it belongs to the html structure, not the text data. You have to mark them as "no, this is just text data, not a control character" for html parsers. One way to do this is to send entities instead of the "real" character itself, e.g. &lt; instead of <
The function htmlspecialchars() takes care of those characters that always have a special meaning in (x)html.
You might also want to enclose the output in a <pre>....</pre> element to keep the formatting of print_r().

echo '<pre>', htmlspecialchars(print_r($myStuff, true)), "</pre>\n";
VolkerK
Finally! It took 5 answers before someone mentioned htmlspecialchars.
David Dorward