使用DOM和xpath样式化未样式化的链接 [英] Style unstyled links with DOM and xpath

查看:56
本文介绍了使用DOM和xpath样式化未样式化的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我要构建的系统,我定义了存储在LINKSTYLE中的通用style,该通用style应该应用于尚未设置样式(内联)的a元素.我对DOMDocumentxpath不太熟悉,我无法弄清楚出了什么问题.

For a system I am building I am defining a general style stored in LINKSTYLE that should be applied to a elements that are not yet styled (inline). I am not very experienced with the DOMDocument or xpath and I can't figure out what is going wrong.

感谢Gordon我已经更新了代码:

Thanks to Gordon I've updated my code:

libxml_use_internal_errors(true);    

$html  = '<a href="#">test</a>'.
         '<a href="#" style="border:1px solid #000;">test2</a>';

$dom    = new DOMDocument();
$dom->loadHtml($html);
$dom->normalizeDocument();  
$xpath = new DOMXPath($dom);

foreach($xpath->query('//a[not(@style)]') as $node)
    $node->setAttribute('style','border:1px solid #000');

return $html;

使用此更新代码,我不会再收到任何错误,但是a元素没有样式.

With this updated code I receive no more errors, however the a element does not get styled.

推荐答案

使用libxml_use_internal_errors(true)抑制源于loadHTML的解析错误.

Use libxml_use_internal_errors(true) to suppress parsing errors stemming from loadHTML.

  • libxml_use_internal_errors() — Disable libxml errors and allow user to fetch error information

XPath查询无效,因为contains期望在style属性中搜索一个值.

The XPath query is invalid because contains expects a value to search for in the style attribute.

如果要查找所有没有样式元素的锚点,只需使用

If you want to find all anchors without a style element, just use

//a[not(@style)]

您没有看到更改,因为您返回的是存储在$ html中的字符串.用DOMDocument加载字符串后,必须先运行查询并修改DOMDocument对该字符串的内部表示形式,然后将其序列化.

You are not seeing your changes, because you are returning the string stored in $html. Once you loaded the string with DOMDocument, you have to serialize it back after you have have run your query and modified the DOMDocument's internal representation of that string.

示例(演示)

Example (demo)

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

输出:

<ul>
<li><a href="#foo" style="font-weight:bold">foo</a></li>
    <li><a href="#bar" style="font-weight:bold">bar</a></li>
    <li><a href="#baz" style="font-weight:bold">baz</a></li>
</ul>

请注意,为了将 saveHTML与参数一起使用,您需要至少需要PHP 5.3.6.

Note that in order to use saveHTML with an argument, you need at least PHP 5.3.6.

这篇关于使用DOM和xpath样式化未样式化的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆