首页 > 解决方案 > 如何使用foreach循环将html字符串存储在php变量中

问题描述

我是新手php。这与wordpress有关,我非常困惑。

基本上,我将一个名称数组从另一个文件(通过ajaxjson)传递到一个php函数中。此函数将遍历每个名​​称并生成html代码以显示到带有图像的页面。我想将此html代码作为字符串存储到一个变量中,以便在我的应用程序的另一部分中使用(特别是将其附加到帖子以实时更新,但这是一个单独的问题)。

我的ajax回复显示了我想要的结果,只是没有存储在字符串中。它还说,尽管路径正确,但找不到我的图像的路径。似乎我要么连接了错误的东西,要么把引号放在了错误的地方,或者其他的东西。我想将所有html生成的内容存储在$html_string其中(我知道在此处显示代码时无法正确加载我的应用程序,这只是我尝试过的最后一件事,所以我把它留在了那里)。

我的代码:

<?php

add_action('wp_ajax_nopriv_test_function', 'test_function');
add_action('wp_ajax_test_function', 'test_function');

function test_function() {
  if ( isset($_POST) ) {

        $nameData = $_POST['nameData'];


        //Strip any double escapes then use json_decode to create an array.
        $nameDecode =  json_decode(str_replace('\\', '', $_POST['nameData']));

        // Anything outputted will be returned in the response
        foreach ($nameDecode as $key => $name) {
        $html_string .=  ?>  <img src="<?php bloginfo('template_directory');?>/images/baseball/team0.jpg"> <p> <?php echo $name  ?> <p /> '
      <?php ' }
        echo json_encode($html_string);

        // print_r($html_string);

    }
  die();
}  ?>

电流输出:

ajax success!           <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> Eleanora <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> Eleanora <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> george <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> george <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> george <p />
      null
card-store.local/:1 GET http://card-store.local/%22http:/card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg/ 404 (Not Found)

期望的输出:

$html_string = '<img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> Eleanora <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> Eleanora <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> george <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> george <p />
                <img src="http://card-store.local/wp-content/themes/card-store-theme/images/baseball/team0.jpg"> <p> george <p />';

我怎样才能做到这一点?

标签: phpwordpress

解决方案


你可以试试这个

 foreach ($nameDecode as $key => $name) {
            $html_string .= '<img src="'.bloginfo('template_directory').'"/images/baseball/team0.jpg"> <p>'.$name.' <p />';
        }

推荐阅读