如何使用 php 中的 dom 删除 class?

how to remove a class using dom in php?

我想删除包含引用的 class "refs"。我从中获取内容的页面(http://www.sacred-destinations.com/mexico/palenque)如下所示:

 <div class="col-sm-6 col-md-7" id="essay">
    <section class="refs">
    </section>
    </div><!-- end #essay -->

现在我不知道如何删除这个 'refs' class 因为它包含在 "section" 之类的东西中.. 这是我到目前为止所做的事情...

<?php
$url="http://www.sacred-destinations.com/mexico/palenque";
 $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    $html = curl_exec($ch);
    curl_close($ch);
    $newDom = new domDocument;
    libxml_use_internal_errors(true);
    $newDom->loadHTML($html);
    libxml_use_internal_errors(false);
    $newDom->preserveWhiteSpace = false;
    $newDom->validateOnParse = true;
    $sections = $newDom->saveHTML($newDom->getElementById('essay'));
$text=$sections->find('<section class="refs">');
$result=removeClass($text);
echo $result;
?>

DOM文档没有 find() 方法,您必须使用带有 XPath 表达式的 DOMXPath::evaluate()。

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_use_internal_errors(false);
$dom->preserveWhiteSpace = false;
$xpath = new DOMXPath($dom);

$expression = 
  '//div[
     @id="essay"
   ]
   /section[
     contains(
       concat(" ", normalize-space(@class), " "), " refs "
     )
   ]';

foreach ($xpath->evaluate($expression) as $section) {  
  $section->removeAttribute('class');
}
echo $dom->saveHtml();

Class 属性可以包含多个值,如 classOne classTwo。使用 normalize-space(),空格将减少为字符串内的单个空格(删除开始和结束)。 concat() 在开头和结尾添加空格。这避免将 class 名称匹配为另一个 class 名称的一部分。

在示例中,整个 class 属性将被删除。要修改它,您可以使用 DOMElement::getAttribute() 读取它并使用字符串函数来更改它。

这里有几个基于 DOM 的库,可以使 HTML 操作更容易。