I use PHP Dom Document to read HTML Dom elements from file.
$html = file_get_contents(public_path() . 'content.html');
$dom = new \DOMDocument();
$dom->loadHTML($html);
var_dump($dom->getElementById('panel_header'));
I can target the element by its ID, and read the contents of an element and more.
But i can't find its style properties.
Because i need to clone it or change with new parameters.
How to read its style properties and change ?
Is it possible ?
Any other solutions ?
you can try this:If CSS is on the same page you can try this:
$html = file_get_contents('testing.html');
$dom = new DOMDocument();
$dom->loadHTML($html);
$div = $dom->getElementById('test');
if ($div->hasAttributes()) {
foreach ($div->attributes as $attr) {
$name = $attr->nodeName;
$value = $attr->nodeValue;
if( strcmp($name,"class") == 0){
$x=getStyle($dom->textContent,".$value{","}");
echo "<pre>";
print_r($x);
}
if( strcmp($name,"id") == 0){
$idCss=getStyle($dom->textContent,"#$value{","}");
echo "<pre>";
print_r($idCss);
}
}
}
function getStyle($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$len = strpos($string, $end, $ini);
return substr($string, $ini, $len);
}
to update the style you can use.
$div->setAttribute('style', 'background-color:blue;');
echo $dom->saveHTML(); exit;.
testing.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="test" class="stl" style="width:100px;">
</div>
</body>
</html>
<style>
.stl{
background-color:green;
}
</style>
output:
.stl{
background-color:green;
}
if you are looking for only style you can do this:
$html = file_get_contents('testing.html');
$dom = new DOMDocument();
$dom->loadHTML($html);
$div = $dom->getElementById('test');
if ($div->hasAttributes()) {
echo $div->getAttribute('style');//width:100px;
}
A DOM parser will only let you read data that is in the DOM.
It won't load CSS, apply it to the DOM, and then provide you access to the computed properties of the element.
To achieve that you need to take a different approach and use a tool which does apply CSS to the DOM. The most common ones are Selenium and PhantomJS (PHP bindings are available) (they also execute JavaScript).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With