You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过PHP循环为邮件模板动态生成HTML元素展示多账号信息?

问题原因

  • 外层循环中每次执行$w_body = file_get_contents(...)都会覆盖之前拼接的内容,最终$w_body只会保留最后一次循环替换的结果
  • 现有模板仅包含单个用户的展示结构,没有预留多用户列表的占位符,无法直接循环生成多个模块

解决方案

第一步:调整HTML邮件模板

把单个用户展示部分抽离,主模板预留多用户列表占位符%user_list%,修改后主模板的用户信息区域如下:

<!-- USER INFO  -->
<tr>
  <td class="user_detail_area borderbottom">
    <table width="97%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td class="user_info">
           ユーザー名の確認を受け付けました。本メールアドレスには以下のユーザー名が紐づいています。                
        </td>
      </tr>
      <tr>
        <td class="user_info_blockquote">
          %user_list%      
        </td>
      </tr>
      <tr><td><br></td></tr>
    </table>
  </td>
</tr>
<!-- USER INFO END -->

第二步:调整PHP逻辑

HTML模板本质就是字符串,你可以把需要循环生成的单个用户结构作为独立子模板,循环处理完所有数据生成对应内容拼接后,再替换入主模板即可,修改后代码如下:

// 先读取主模板,全局只需要读取一次
$mainTpl = file_get_contents('../../../framework/src/function/html_templates/forgot_username.html');
// 定义单个用户信息的子模板
$userItemTpl = '<p class="blockquote">
     <font style="color: #03abf2"> ユーザー名: </font> %username% <br>
     <font style="color: #03abf2"> 所属会社: </font> %company% / %company2%
</p>';
$userListHtml = '';

// 循环生成所有用户的展示块
for ($i=0; $i < count($w_user_id_infos); $i++) { 
    $replaceUsername = $w_user_id_infos[$i]["login_cd"];
    for ($j=0; $j < count($w_user_id_infos[$i]["customer_info"]); $j++) { 
        $w_customer_name1_text = $w_user_id_infos[$i]["customer_info"][$j]["customer_name1_text"];
        $w_customer_name2_text = $w_user_id_infos[$i]["customer_info"][$j]["customer_name2_text"];
        // 替换单个用户的内容
        $tmpItem = str_replace(
            ['%username%', '%company%', '%company2%'],
            [$replaceUsername, $w_customer_name1_text, $w_customer_name2_text],
            $userItemTpl
        );
        // 把当前用户块拼接到总用户列表
        $userListHtml .= $tmpItem;
    }
}

// 把生成好的完整用户列表替换到主模板
$w_body = str_replace('%user_list%', $userListHtml, $mainTpl);

// 后续发信逻辑保持不变
$data = explode(',', $_SESSION['icon_data']);
$image_data = base64_decode($data[1]);
f_common_send_mail($w_addr, $w_subject, $w_body, $image_data);

内容的提问来源于stack exchange,提问作者funtkungus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 20:06:03