Heim  >  Artikel  >  Backend-Entwicklung  >  PHP如何将输出的内容放到一个变量中

PHP如何将输出的内容放到一个变量中

WBOY
WBOYOriginal
2016-06-06 20:10:401225Durchsuche

我也不知道我问题标题的描述是否正确。

我正在做一个项目,里面用到了一些php + html格式的代码,然后我需要把上面的所有的输出的html结果保存到一个缓存中。

我现在唯一的办法就是把要保存的php+html格式代码写成类似

$cache = "html".php."html";
然后才能缓存这个$cache变量。

有没有办法让我把这些php + html代码放到一个文件中,然后读取他们输出的效果到一个变量里面?


例如我有这么一些代码

<code><div class="article row_3" onmouseover="this.style.cssText='background-color:<?php echo $hue[$i-1]; ?>'" onmouseout="this.style.cssText='background: #333;'">
     <p><?php $post_describe = get_post_meta($post->ID,'post_describe',true);if(!$post_describe){echo strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 142, '');}else{echo $post_describe;}?></p>
</div></code>

代码中有一些if判断之类的语句,我不方便吧他们全部写在一行,然后丢一个变量里面。这样很不利于后期修改。

所以我寻求其他更好的办法。


我发现使用include 会直接输出文件中的内容,而不会返回内容给一个变量。

回复内容:

我也不知道我问题标题的描述是否正确。

我正在做一个项目,里面用到了一些php + html格式的代码,然后我需要把上面的所有的输出的html结果保存到一个缓存中。

我现在唯一的办法就是把要保存的php+html格式代码写成类似

$cache = "html".php."html";
然后才能缓存这个$cache变量。

有没有办法让我把这些php + html代码放到一个文件中,然后读取他们输出的效果到一个变量里面?


例如我有这么一些代码

<code><div class="article row_3" onmouseover="this.style.cssText='background-color:<?php echo $hue[$i-1]; ?>'" onmouseout="this.style.cssText='background: #333;'">
     <p><?php $post_describe = get_post_meta($post->ID,'post_describe',true);if(!$post_describe){echo strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 142, '');}else{echo $post_describe;}?></p>
</div></code>

代码中有一些if判断之类的语句,我不方便吧他们全部写在一行,然后丢一个变量里面。这样很不利于后期修改。

所以我寻求其他更好的办法。


我发现使用include 会直接输出文件中的内容,而不会返回内容给一个变量。

这是个好问题。实际上这就是在直接把php当模板语言来用。

http://php.net/manual/en/function.includ...

看这里的 Example #6 Using output buffering to include a PHP file into a string

不被php代码约束的内容输出到响应,你是阻拦不了的,只能这样用重定向的方法来捕获之。

解决了,在include中间加入

<code>ob_start();
 你的代码
$html = ob_get_contents();
ob_end_clean();</code>

ob_start之后可以把输出的内容放到缓冲区内,而不是直接返回给用户,然后通过ob_get_contents获取到

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn