【问题标题】:Insert text after/before an self-closing tag using DOM in PHP?在 PHP 中使用 DOM 在自闭合标记之后/之前插入文本?
【发布时间】:2011-06-18 02:43:08
【问题描述】:
$imgs = $xpath->query('//img');
$i = 0;
foreach($imgs as $img) {
    $before = new DOMText($captions[$i]);
    $img->parentNode->insertBefore($before);
    $i++;
}

我想在标签前插入一些文本,但是我不能让它工作。文本有时会插入错误的位置。我该如何解决这个问题?

【问题讨论】:

    标签: php dom insert tags


    【解决方案1】:

    试试:

    $img->parentNode->insertBefore($before, $img);
    

    $img 作为参数(“引用节点”)添加到插入函数中,显式告诉插入您要在层次结构中的哪个位置插入新节点。否则,文档只会说“附加到子节点”,这意味着新节点将是父节点的最后一个子节点。

    例如

       <span>  <-- parentNode
          <b>This is some text before the image</b>
          <img ...>   <--- $img node
          <i>This is some text after the image</b>
       </span>
    

    没有额外的参数,你会得到:

      <span>
         <b>...</b>
         <img ...>
         <i>...</i>
         new text node here   <-- appended to parent Node's children, e.g. last
      </span>
    

    有了参数,你会得到:

      <span>
         <b>...</b>
         new text node here   <--the "before" position
         <img ...>
         <i>...</i>
      </span>
    

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2012-02-03
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多