我有两个php变量:
1)$item1 = "baking";
2)$item2 = "fun"
;
这些变量需要插入到下面的DOM结构中。
<random>
<li>
I also think <star item="1"/> can be <star item="2"/> sometimes.
</li>
</random>
我使用以下代码获取“li
”元素。
$elements = $dom->getElementsByTagName('li');
foreach ($elements as $node) {
$sentence = $node->nodeValue;
// This will currently print "I also think can be sometimes."
}
如何将baking
插入<star item="1"/>
所在位置fun
插入<star item="2"/>
所在位置,以便最终结果为: < / p>
I also think baking can be fun sometimes.
答案 0 :(得分:1)
这是一个快速实施配合,根据您的需要进行调整:
<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<random>
<li>
I also think <star item="1"/> can be <star item="2"/> sometimes.
</li>
</random>
XML;
$dom = new DOMDocument;
$dom->loadXML($xml);
$liElements = $dom->getElementsByTagName('li');
$starElements = $dom->getElementsByTagName('star');
$i = $starElements->length - 1;
while ($i > -1) {
$starElement = $starElements->item($i);
if ( $starElement->nodeName == 'star' ) {
if ($starElement->getAttribute('item') == 1) {
$newelement = $dom->createTextNode('baking');
$starElement->parentNode->replaceChild($newelement, $starElement);
} else if ($starElement->getAttribute('item') == 2) {
$newelement = $dom->createTextNode('fun');
$starElement->parentNode->replaceChild($newelement, $starElement);
}
}
$i--;
}
foreach ($liElements as $node) {
echo $node->nodeValue;
}
?>
http://sandbox.onlinephpfunctions.com/code/4aa46eb297f49ea4f2302ac265c0dd805925b657