如何在纯 PHP 中获取起始 HTML 标签?

How to get the starting HTML tag in pure PHP?

我需要获取现有表单的起始 <form> 标记,原样 带有属性 ,没有内容和结束 </form> 标记,将它用于新的动态创建的表单。所以,我只需要字符串 <form method="post" class="form" data-id="19" data-title="Schema" data-slug="schema" data-message-success="Success!" data-message-invalid-email="Not valid!" data-message-required-field-missing="All fields are required!" data-message-error="Error!"> How to do this in pure PHP?

我的表格:

<form method="post" class="form" data-id="19" data-title="Schema" data-slug="schema" data-message-success="Success!" data-message-invalid-email="Not valid!" data-message-required-field-missing="All fields are required!" data-message-error="Error!">

--- Form content ---

</form>

现在我只找到了如何获取表单属性以将它们添加到新表单中。我知道,我可以遍历它并创建新表单,但我不是专家,我想可能存在更优雅的解决方案。

function parseTag($content,$tg) {
    $dom = new DOMDocument('1.0', 'utf-8');
    $dom->loadHTML($content);
    $attr = array();
    foreach ($dom->getElementsByTagName($tg) as $tag) {
        foreach ($tag->attributes as $attribName => $attribNodeVal) {
            $attr[$attribName]=utf8_decode($tag->getAttribute($attribName));
        }
    }
    return $attr;
}

//$html variable contain the above form
$attrib_arr = parseTag($html,'form');
var_dump($attrib_arr);

输出:

array(9) {
  ["method"]=>
  string(4) "post"
  ["class"]=>
  string(19) "form"
  ["data-id"]=>
  string(2) "19"
  ["data-title"]=>
  string(23) "Schema"
  ["data-slug"]=>
  string(27) "schema"
  ["data-message-success"]=>
  string(50) "Success!"
  ["data-message-invalid-email"]=>
  string(52) "Not valid!"
  ["data-message-required-field-missing"]=>
  string(41) "All fields are required!"
  ["data-message-error"]=>
  string(25) "Error!"
}

据我了解您的问题,您需要带有属性的开始表单标签。为此,您可以使用如下内容:

<?php
declare(strict_types=1);

$html = <<<HTML
<form method="post" class="form" data-id="19" data-title="Schema" data-slug="schema" data-message-success="Success!" data-message-invalid-email="Not valid!" data-message-required-field-missing="All fields are required!" data-message-error="Error!">
    --- Form content ---
    <div>with some tags</div>
</form>
HTML;

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);

foreach ($xpath->query('//form') as $formTag) {
    // remove child nodes of the form tag
    foreach ([...$formTag->childNodes] as $child) {
        $formTag->removeChild($child);
    }

    // output as string, but remove the closing tag
    echo substr($doc->saveHTML($formTag), 0, -7);
}

(Demo)