PHP - DOMDoc - 选择上一个元素及其属性

时间:2015-04-09 12:37:55

标签: php xml dom nodes

我正在尝试从字符串管理DOMDocument。 我的字符串看起来像这样:

$String =
    <p>
        <div class="ST" data-start="1" data-end="5">
            <span>WORD1</span><span>WORD2</span>
        </div>
    </p>
    <p>
        WORD3 WORD4
    </p>
    <p>
        <div class="ST" data-start="6" data-end="10">
            <span>WORD5</span><span>WORD6</span>
        </div>
    </p>

我的目标是将WORD3WORD4添加到<div>标记WORD1 WORD2WORD5 WORD6中对于第一个和最后一个<p>标记。另外,我需要获得之前data-start的{​​{1}} data-end并获得最终结果:

p > div

我设法将$String = <p> <div class="ST" data-start="1" data-end="5"> <span>WORD1</span><span>WORD2</span> </div> </p> <p> <div class="ST" data-start="1" data-end="5"> WORD3 WORD4 </div> </p> <p> <div class="ST" data-start="6" data-end="10"> <span>WORD5</span><span>WORD6</span> </div> </p> WORD3放入WORD4,但我不知道如何获取前一个元素<div>并获取其属性{{1} }和p > div ...

我的代码:

data-start

事实上,对于data-endpublic function reverseTransform($value) { $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadHTML($value); $pTags = $dom->getElementsByTagName('p'); $TagFull=''; foreach ($pTags as $pTag) { $valuePTagFull = $this->DOMinnerHTML($pTag); if (strpos($valuePTagFull,'<div') === false) { $valuePTagFull = "<div class='st'>".$valuePTagFull."</div>"; } $TagFull .= $valuePTagFull; } } private function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $element->ownerDocument->saveHTML($child); } return $innerHTML; } 但没有<p>的每个WORDx,我将<div>包裹在WORDx <div>data-start

data-end属性

但是如何使用DOM,XML或其他方式从前一个元素中选择和获取属性?

谢谢!

0 个答案:

没有答案