【问题标题】:Best way to modify html form elements with php?用php修改html表单元素的最佳方法?
【发布时间】:2012-09-08 20:34:23
【问题描述】:

如何使用 PHP 修改和插入表单元素?

我有一个表单分配给 PHP 中的变量,如下所示:

$the_original_form = '
<form method="post" action="whatever.php">
<input type="text" name="iamtextfield" id="textisme">
<input type="file" name="iamfilefield" id="fileisme">
<input type="hidden" name="hideme" value="nope">
</form>
';

我有第二个变量:

$put_me_on_the_top = '<div class="getinme">';

还有第三个变量:

$put_me_on_the_bottom = '</div><div class="justsomethingelse">hi there</div>';

和一个修改过的表单元素:

$i_have_changed = '<input type="file" name="filepartdeux" id="iamabetterfile">';

我想最终得到:

$the_modified_form = '
<form method="post" action="whatever.php">
<input type="text" name="iamtextfield" id="textisme">
<div class="getinme">
    <input type="file" name="filepartdeux" id="iamabetterfile">
</div>
<div class="justsomethingelse">hi there</div>
<input type="hidden" name="hideme" value="nope">
</form>
';

【问题讨论】:

  • 使用DOM
  • 您的问题不清楚:听起来您尝试使用 PHP(服务器端)来修改客户端(您应该使用 Javascript/jQuery 做的事情)。
  • 我真的不希望客户修改我的表单。我更愿意在服务器端做。但我不确定我是否最好使用 php dom、xpath 或 regex

标签: php html regex dom xpath


【解决方案1】:

您可以将格式错误或格式正确的 HTML 文档加载到新的 DOMDocument 中,并像处理 XML 一样对其进行操作。

$doc = new DOMDocument();

$doc->loadHTML($the_original_form);

// You can manipulate using the DOM object just follow the PHP manual for usage
foreach ($doc->childNodes as $element)
{
    // Evaluate elements here and insert / extract / delete as necessary
}
  • 格式错误的 HTML 会从 DOMDocument 中引发错误,您需要处理这些错误的方法。尽可能多地尝试并使用格式良好的 HTML。

【讨论】:

    【解决方案2】:

    检查phpQuery - PHP 的 jQuery 端口。它是在 PHP 中处理 HTML 的非常简单的工具,特别适合具有基本 jQuery 知识的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      相关资源
      最近更新 更多