PHP DOMDocument Makes Sibling The Parent



I have been playing around the the DOMDocument API. I am trying to remove or display certain elements based off of user roles. Sometimes I have to remove the a root most level element. Which seems to work . However I do not want the html or body elements to get appended and so I pass in the option LIBXML_HTML_NOIMPLIED to the DOMDocument and then everything seems to get funky.


Before I start manipulating the HTML my html code looks like this:



<span>This should show up for everyone first</span><p roles="ADMIN">Just Chilling</p><p>This Should show up for anyone</p>


My expected output is:



<span>This should show up for everyone first</span><p>This Should show up for anyone</p>


The output I get is:



<span>This should show up for everyone first<p>This Should show up for anyone</p></span>


Notice the span somehow becomes the parent of everything else. Which is not desired. This does not happen if the html and body get appended.


Below is my php code. I have tried both loadHTML and loadXML along with saveHTML and saveXML. Both have their poison. I am pretty flexible about which one i use. My goal is to store html code in the database and then display that on the client. I have no need to store the html body or head tags. Any help would be great.



public function filterElementsByAccess($user){
$document = new DOMDocument('1.0', 'UTF-8');
$attribute = 'roles';
$document->loadHTML($this->getContent(), LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
$xpath = new DOMXPath($document);
$roleElements = $xpath->query('//*[@'.$attribute.']');
if(!empty($roleElements)){
foreach($roleElements as $roleElement){
$parentNode = $roleElement->parentNode;
$roleString = (string)$roleElement->getAttribute('roles');
$roles = (array)explode(',', $roleString);
$matchedUserRoles = array();
foreach($roles as $role){
if(!empty($user)){
foreach($user->getUserRoles() as $userRole){
if(trim(strtolower($userRole->getRole()->getname())) == trim(strtolower($role))){
array_push($matchedUserRoles, $role);
}
}
}
}
if(count($matchedUserRoles) == count($roles)){
$roleElement->removeAttribute($attribute);
}else{
$parentNode->removeChild($roleElement);
}
}
}
/*
* This prevents <?xml version=\"1.0\"?> from being outputted since we are using loadXML and not loadHTML cause of custom tags
*/
$this->setContent(($document->documentElement != null) ? $document->saveXML($document->documentElement) : null);
}

No comments:

Post a Comment