Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Style unstyled links with DOM and xpath

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.

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;

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)]

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));

Output:

<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>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...