如何使用DomDocument向现有的HTML添加元素


How to add elements to existing HTML using DomDocument?

我有以下选择下拉

<select name="set_login_redirect" id="set_login_redirect">
    <option value="dashboard">WordPress Dashboard</option>
    <option class="level-0" value="1881">Activate</option>
    <option class="level-0" value="2109">Affiliate Area</option>
    <option class="level-0" value="429">Cart</option>
    <option class="level-0" value="430">Checkout</option>
</select>

如何使用PHP DomDocument类将新的option元素添加到select下拉列表中

例如,我想将下面的代码添加到上面的HTML中。

怎么做呢?

<option class="level-0" value="27">The Word</option>

我无法得到答案,所以写了一个PHP函数与一些肮脏的正则表达式来解决它。

/**
 * Append an option to a select dropdown
 *
 * @param string $option option to add
 * @param string $select select dropdown
 *
 * @return string
 */
function pp_append_option_to_select($option, $select) {
    $regex = "/<select ([^<]*)>/";
    preg_match($regex, $select, $matches);
    $select_attr = $matches[1];
    $a = preg_split($regex, $select);
    $join = '<select ' . $select_attr . '>' . "'r'n";
    $join .= $option . $a[1];
    return $join;
}

$a = pp_append_option_to_select('<option value="current">Current page</option>', $xml);
print_r($a);

希望有一天有人会发现这有用。

我仍然愿意使用更好的方法来使用domdocument类。