0

大家好!

我是一门课程的学生,正在尝试创造一些东西。我一直在尝试改变 '<'li'>' 的样式,它包含一个 '<'span'>' 标签,其余的 '<'li'>' 标签应该保持原样。这就是我到目前为止的方式:

<?php
$html = <<< HTML
<ul>
    <li><span style="font-weight:bold;color:white;">foo</span></li>
    <li style="color: brown;"><a href="#bar">bar span</a></li>
    <li><span><a href="#baz">baz</a></span></li>
</ul>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//li[not(@style)]/span[not(@style)]') as $node) {
    $node->setAttribute('style', 'font-weight:bold; background:black;');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0)); 

?>

所以这导致:

<ul>
<li><span style="font-weight:bold;color:white;">foo</span></li>
    <li style="color: brown;"><a href="#bar">bar span</a></li>
    <li><span style="font-weight:bold; background:black;"><a href="#baz">baz</a></span></li>
</ul>

我需要实现的是:

<ul>
<li><span style="font-weight:bold;color:white;">foo</span></li>
    <li style="color: brown;"><a href="#bar">bar span</a></li>
    <li style="font-weight:bold; background:black;"><span><a href="#baz">baz</a></span></li>
</ul>

所以我想设计 li 而不是跨度!

请帮助学习者,只是尝试了很多,无法找到解决方法。

这是正确的方法吗???

<?php
$url ='http://3d.te.ua/xpath/ria.html';
$html = file_get_contents($url);
$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//li[not(@style)]/span[not(@style)]') as $node) {
    $node->parentNode->setAttribute('style', 'font-weight:bold; background:black;');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0)); 

?>
4

1 回答 1

0

用于/..选择父节点:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//li[not(@style)]/span[not(@style)]/..') as $node) {
    $node->setAttribute('style', 'font-weight:bold; background:black;');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0)); 
于 2013-04-18T23:32:57.570 回答