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.
Use
libxml_use_internal_errors(true)to suppress parsing errors stemming fromloadHTML.libxml_use_internal_errors()— Disable libxml errors and allow user to fetch error informationThe XPath query is invalid because
containsexpects a value to search for in the style attribute.fn:contains($arg1 as xs:string?, $arg2 as xs:string?) as xs:booleanIf you want to find all anchors without a style element, just use
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)
Output:
Note that in order to use
saveHTMLwith an argument, you need at least PHP 5.3.6.