PHP ob_get_clean removing newlines after ?>
I am trying to create a function that grabs a script file and executes the output on a telnet device. I have it working, but ob_get_clean seems to be removing any newlines after a 开发者_JAVA技巧php closing brace (?>). Has anyone encountered this problem?
public final function execScript($name, $args)
{
ob_start();
include("../apps/frontend/modules/device/scripts/" . $name . ".php");
$partial = ob_get_clean();
$commands = explode("\n", $partial);
foreach($commands as $command)
{
$output .= $this->telnet->exec($command);
}
return $output;
}
"Script"
conf
int ethernet 1/<?php echo $args['port']; ?>
switchport allowed vlan add <?php echo $args['vlan_id']; ?> tagged
switchport native vlan <?php echo $args['vlan_id']; ?>
switchport allowed vlan remove 1
end
Expected Output
conf
int ethernet 1/18
switchport allowed vlan add 100 tagged
switchport native vlan 100
switchport allowed vlan remove 1
end
Actual Output
conf
int ethernet 1/18switchport allowed vlan add 100 tagged
switchport native vlan 100switchport allowed vlan remove 1
end
One newline will always be ignored after a closing ?>
tag -- using output buffering doesn't change anything.
As a reference, see Instruction separation :
The closing tag for the block will include the immediately trailing newline if one is present.
And Escaping from HTML :
when PHP hits the
?>
closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation )
According to those two sentences from the PHP manual (and from my own experience), losing a newline after the ?>
, like you do, is documented and expected behavior1.
1.Even if surprising, the first time you encounter it ^^
Yes, PHP does that - it removes one single newline after the ?>
It does that because in a normal PHP file, you close it with ?> then you have a trailing newline which would often mess things up.
In your case, it's not helping.
I would do this:
conf
int ethernet 1/<?php echo $args['port'] . "\n";
?>switchport
I moved the closing ?> to the next line just so you are not depending on newline removal.
精彩评论