【问题标题】:PHP DomDocument - how to append string containing html tags?PHP DomDocument - 如何附加包含html标签的字符串?
【发布时间】:2014-03-14 13:58:13
【问题描述】:

我有一个方法返回那些类型的字符串:

string(6) "<math>"
string(12) " <semantics>"
string(8) "  <mrow>"
string(29) "   <mi>A</mi><mrow><mo>(</mo>"
string(14) "    <mi>T</mi>"
string(27) "   <mo>)</mo></mrow></mrow>"
string(13) " </semantics>"
string(7) "</math>"

我的目标是将其附加到 DOMDocument。是否有可能检查我的字符串中是否有标签,所以应该将标签添加为子项,而不是节点值。

提前谢谢你。

【问题讨论】:

  • 是指将它们全部转换为 HTML 节点并将它们附加到 DOMDocument 节点吗?
  • 对,我刚刚有了一个想法:将它们放在一个字符串中并使用 domdocument loadhtml
  • 好的,我正在为您准备解决方案;你能告诉我你是在循环中调用你的方法,每次它返回一个字符串还是只返回一个字符串数组?

标签: php html dom tags domdocument


【解决方案1】:

我想这可能对你有帮助

//I assume the name of your method is "getStringsNodes()" and it returns the array of strings
$string_array = getStringNodes();
$string_array = array_map('trim', $string_array);
$string_xml = implode('', $string_array);
$new_nodes = new DomDocument();
$new_nodes->loadXML($string_xml);
$first_node = $new_node->getElementsByTagName('math')->item(0);

//I assume the parent XML container is $owner_xml
$owner_xml = new DomDocument();
$owner_xml->loadXML('<sample><parent_node></parent_node></sample>'); //convert this to whatever you need
$node = $owner_xml->importNode($first_node, true);
$parent_node = $owner_xml->getElementsByTagName('parent_node')->item(0);
$parent_node->appendChild($node);

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多