Класс DOMElement
Обзор классов
Свойства
— Пока не реализовано, всегда возвращает NULL
Примечания
Расширение DOM использует кодировку UTF-8. Используйте функции utf8_encode() и utf8_decode() для работы с текстами в кодировке ISO-8859-1, либо Iconv в других кодировках.
Содержание
- DOMElement::__construct — Создание нового объекта класса DOMElement
- DOMElement::getAttribute — Возвращает значение атрибута
- DOMElement::getAttributeNode — Возвращает узел атрибута
- DOMElement::getAttributeNodeNS — Возвращает узел атрибута
- DOMElement::getAttributeNS — Возвращает значение атрибута
- DOMElement::getElementsByTagName — Возвращает элементы по имени тэга
- DOMElement::getElementsByTagNameNS — Получение элементов по локальному имени в заданном пространстве имен
- DOMElement::hasAttribute — Проверяет наличие атрибута
- DOMElement::hasAttributeNS — Проверяет, существует ли заданный атрибут
- DOMElement::removeAttribute — Удаляет атрибут
- DOMElement::removeAttributeNode — Удаляет атрибут
- DOMElement::removeAttributeNS — Удаляет атрибут
- DOMElement::setAttribute — Устанавливает значение атрибута
- DOMElement::setAttributeNode — Добавляет новый узел атрибута к элементу
- DOMElement::setAttributeNodeNS — Добавляет новый атрибут к элементу
- DOMElement::setAttributeNS — Добавляет новый атрибут
- DOMElement::setIdAttribute — Объявляет атрибут с заданным именем ключевым атрибутом
- DOMElement::setIdAttributeNode — Объявляет заданный узал атрибута ключевым
- DOMElement::setIdAttributeNS — Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим
Описание класса domelement, примеры использования класса domelement.
Источник
Класс DOMElement
Обзор классов
Свойства
Пока не реализовано, всегда возвращает NULL
Примечания
Расширение DOM использует кодировку UTF-8. Используйте функции utf8_encode() и utf8_decode() для работы с текстами в кодировке ISO-8859-1, либо Iconv в других кодировках.
Содержание
- DOMElement::__construct — Создание нового объекта класса DOMElement
- DOMElement::getAttribute — Возвращает значение атрибута
- DOMElement::getAttributeNode — Возвращает узел атрибута
- DOMElement::getAttributeNodeNS — Возвращает узел атрибута
- DOMElement::getAttributeNS — Возвращает значение атрибута
- DOMElement::getElementsByTagName — Возвращает элементы по имени тэга
- DOMElement::getElementsByTagNameNS — Получение элементов по локальному имени в заданном пространстве имен
- DOMElement::hasAttribute — Проверяет наличие атрибута
- DOMElement::hasAttributeNS — Проверяет, существует ли заданный атрибут
- DOMElement::removeAttribute — Удаляет атрибут
- DOMElement::removeAttributeNode — Удаляет атрибут
- DOMElement::removeAttributeNS — Удаляет атрибут
- DOMElement::setAttribute — Устанавливает значение атрибута
- DOMElement::setAttributeNode — Добавляет новый узел атрибута к элементу
- DOMElement::setAttributeNodeNS — Добавляет новый атрибут к элементу
- DOMElement::setAttributeNS — Добавляет новый атрибут
- DOMElement::setIdAttribute — Объявляет атрибут с заданным именем ключевым атрибутом
- DOMElement::setIdAttributeNode — Объявляет заданный узел атрибута ключевым
- DOMElement::setIdAttributeNS — Объявляет атрибут с заданным локальным именем и URI пространства имен идентифицирующим
Источник
Класс DOMElement
(PHP 5, PHP 7, PHP 8)
Обзор классов
Свойства
Пока не реализовано, всегда возвращает null
Примечания
Модуль DOM использует кодировку UTF-8. Используйте utf8_encode() и utf8_decode() для работы с текстами в кодировке ISO-8859-1 или iconv для других кодировок.
Содержание
- DOMElement::__construct — Создаёт новый экземпляр класса DOMElement
- DOMElement::getAttribute — Возвращает значение атрибута
- DOMElement::getAttributeNode — Возвращает узел атрибута
- DOMElement::getAttributeNodeNS — Возвращает узел атрибута
- DOMElement::getAttributeNS — Возвращает значение атрибута
- DOMElement::getElementsByTagName — Возвращает элементы по имени тега
- DOMElement::getElementsByTagNameNS — Получение элементов по локальному имени в заданном пространстве имён
- DOMElement::hasAttribute — Проверяет, существует ли атрибут
- DOMElement::hasAttributeNS — Проверяет, существует ли заданный атрибут
- DOMElement::removeAttribute — Удаляет атрибут
- DOMElement::removeAttributeNode — Удаляет атрибут
- DOMElement::removeAttributeNS — Удаляет атрибут
- DOMElement::setAttribute — Добавляет новый или изменяет существующий атрибут
- DOMElement::setAttributeNode — Добавляет новый узел атрибута в элемент
- DOMElement::setAttributeNodeNS — Добавляет новый атрибут в элемент
- DOMElement::setAttributeNS — Добавляет новый атрибут
- DOMElement::setIdAttribute — Объявляет атрибут, указанный именем, с идентификатором типа
- DOMElement::setIdAttributeNode — Объявляет атрибут, указанный узлом, с идентификатором типа
- DOMElement::setIdAttributeNS — Объявляет атрибут, указанный локальным именем и URI пространства имён, с идентификатором типа
User Contributed Notes 13 notes
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.
If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0)
After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.
The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);
This will give you an XML representation of $domElement.
Combining all th comments, the easiest way to get inner HTML of the node is to use this function:
function get_inner_html ( $node ) <
$innerHTML = » ;
$children = $node -> childNodes ;
foreach ( $children as $child ) <
$innerHTML .= $child -> ownerDocument -> saveXML ( $child );
>
It would be nice to have a function which converts a document/node/element into a string.
Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:
function getInnerHTML ( $Node )
<
$Body = $Node -> ownerDocument -> documentElement -> firstChild -> firstChild ;
$Document = new DOMDocument ();
$Document -> appendChild ( $Document -> importNode ( $Body , true ));
return $Document -> saveHTML ();
>
?>
Although it may be preferable to use the dom to manipulate elements, sometimes it’s useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).
To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):
= » ;
$doc = new DOMDocument ();
$doc -> loadHTMLFile ( $filepath );
$elem = $doc -> getElementById ( $elem_id );
// loop through all childNodes, getting html
$children = $elem -> childNodes ;
foreach ( $children as $child ) <
$tmp_doc = new DOMDocument ();
$tmp_doc -> appendChild ( $tmp_doc -> importNode ( $child , true ));
$innerHTML .= $tmp_doc -> saveHTML ();
>
?>
How to rename an element and preserve attributes:
// Changes the name of element $element to $newName.
function renameElement ( $element , $newName ) <
$newElement = $element -> ownerDocument -> createElement ( $newName );
$parentElement = $element -> parentNode ;
$parentElement -> insertBefore ( $newElement , $element );
$childNodes = $element -> childNodes ;
while ( $childNodes -> length > 0 ) <
$newElement -> appendChild ( $childNodes -> item ( 0 ));
>
$attributes = $element -> attributes ;
while ( $attributes -> length > 0 ) <
$attribute = $attributes -> item ( 0 );
if (! is_null ( $attribute -> namespaceURI )) <
$newElement -> setAttributeNS ( ‘http://www.w3.org/2000/xmlns/’ ,
‘xmlns:’ . $attribute -> prefix ,
$attribute -> namespaceURI );
>
$newElement -> setAttributeNode ( $attribute );
>
$parentElement -> removeChild ( $element );
>
function prettyPrint ( $d ) <
$d -> formatOutput = true ;
echo » ;
>
$xpath = new DOMXPath ( $d );
$elements = $xpath -> query ( ‘/library/data’ );
if ( $elements -> length == 1 ) <
$element = $elements -> item ( 0 );
renameElement ( $element , ‘invites’ );
>
Источник
Document Object Model
User Contributed Notes 38 notes
If you need simple interface to DOM check out phpQuery — jQuery port to PHP:
http://code.google.com/p/phpquery/
It uses CSS selectors to fetch nodes.
Here’s example how it works:
// just one file to include
require( ‘phpQuery/phpQuery.php’ );
// intialize new DOM from markup
phpQuery :: newDocument ( $markup )
-> find ( ‘ul > li’ )
-> addClass ( ‘my-new-class’ )
-> filter ( ‘:last’ )
-> addClass ( ‘last-li’ );
// query all unordered lists in last used DOM
pq ( ‘ul’ )-> insertAfter ( ‘div’ );
// iterate all LIs from last used DOM
foreach( pq ( ‘li’ ) as $li ) <
// iteration returns plain DOM nodes, not phpQuery objects
pq ( $li )-> addClass ( ‘my-second-new-class’ );
>
// same as pq(‘anything’)->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery :: getDocument ();
?>
It uses DOM extension and XPath so it works only in PHP5.
This particular W3C page provides invaluable documentation for the DOM classes implemented in php5 (via libxml2). It fills in plenty of php.net’s gaps:
Some key examples:
* concise summary of the class heirachy (1.1.1)
* clarification that DOM level 2 doesn’t allow for population of internal DTDs
* explanation of DOMNode->normalize()
* explanation of the DOMImplementation class
The interfaces are described in OMG’s Interface Definition Language
I hate DOM model !
so I wrote dom2array simple function (simple for use):
function dom2array($node) <
$res = array();
print $node->nodeType.’
‘;
if($node->nodeType == XML_TEXT_NODE) <
$res = $node->nodeValue;
>
else <
if($node->hasAttributes()) <
$attributes = $node->attributes;
if(!is_null($attributes)) <
$res[‘@attributes’] = array();
foreach ($attributes as $index=>$attr) <
$res[‘@attributes’][$attr->name] = $attr->value;
>
>
>
if($node->hasChildNodes()) <
$children = $node->childNodes;
for($i=0;$i length;$i++) <
$child = $children->item($i);
$res[$child->nodeName] = dom2array($child);
>
>
>
return $res;
>
The project I’m currently working on uses XPaths to dynamically navigate through chunks of an XML file. I couldn’t find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function. Turns out it wasn’t as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans.
Hopefully it’ll save someone else the trouble of reinventing this wheel.
function getNodeXPath ( $node ) <
// REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0.
// Get the index for the current node by looping through the siblings.
$parentNode = $node -> parentNode ;
if( $parentNode != null ) <
$nodeIndex = 0 ;
do <
$testNode = $parentNode -> childNodes -> item ( $nodeIndex );
$nodeName = $testNode -> nodeName ;
$nodeIndex ++;
// PHP trickery! Here we create a counter based on the node
// name of the test node to use in the XPath.
if( !isset( $ $nodeName ) ) $ $nodeName = 1 ;
else $ $nodeName ++;
// Failsafe return value.
if( $nodeIndex > $parentNode -> childNodes -> length ) return( «/» );
> while( ! $node -> isSameNode ( $testNode ) );
// Recursively get the XPath for the parent.
return( getNodeXPath ( $parentNode ) . «/ < $node ->nodeName > [ <$ $nodeName >]» );
> else <
// Hit the root node! Note that the slash is added when
// building the XPath, so we return just an empty string.
return( «» );
>
>
?>
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.
DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR
DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID
PHP 5.1 users are encouraged to use the new constants.
If you are using not object-oriented functions and it takes too much time to change them all (or you’ll be replacing them later) then as a temporary decision can be used this modules:
After searching how to extend the DOMDocument and DOMElement I found a way in the bug: http://bugs.php.net/bug.php?id=35104. The following code shows how:
class extDOMDocument extends DOMDocument <
public function createElement ( $name , $value = null ) <
$orphan = new extDOMElement ( $name , $value ); // new sub-class object
$docFragment = $this -> createDocumentFragment (); // lightweight container maintains «ownerDocument»
$docFragment -> appendChild ( $orphan ); // attach
$ret = $docFragment -> removeChild ( $orphan ); // remove
return $ret ; // ownerDocument set; won’t be destroyed on method exit
>
// .. more class definition
>
class extDOMElement extends DOMElement <
function __construct ( $name , $value = » , $namespaceURI = null ) <
parent :: __construct ( $name , $value , $namespaceURI );
>
// . more class definition here
>
$doc = new extDOMDocument ( ‘test’ );
$el = $doc -> createElement ( ‘tagname’ );
$el -> setAttribute ( «attr» , «val» );
$doc -> appendChild ( $el );
// append discards the DOMDocumentFragment and just adds its child nodes, but ownerDocument is maintained.
echo get_class ( $el ). «
» ;
echo get_class ( $doc -> documentElement ). «
» ;
echo » » . $doc -> saveXML (). » » ;
?>
I wrote a framework to implement the StyleSheet interfaces as specified on the W3C website. The code is written in PHP, and is NOT a complete implementation. Use it how ya like. I was planning on adding the CSSStyleSheet interfaces as well. Feel free to ask.
function __set($property, $val) <
if($property == ‘length’)
return true;
>
function item( $index ) <
return $this->self[$index];
>
>
class MediaList extends StyleSheetList <
function appendMedium ( $newMedium ) <
array_push($this->self, $newMedium);
>
function deleteMedium ( $oldMedium ) <
foreach($this->self as $item) <
if( $item == $oldMedium ) <
$item = $this->self[ $this->length-1 ];
array_pop($this->self);
break;
>
>
>
>
class DocumentStyle <
public styleSheets;
function __construct ( ) <
$this->styleSheets = new StyleSheetList();
>
function __set($property, $val) <
if($property == ‘styleSheets’)
return true;
>
>
class LinkStyle <
public sheet;
function __construct () <
$this->sheet = new StyleSheet();
>
function __set($property, $val) <
if($property == ‘sheet’)
return true;
>
>
class StyleSheet <
public type;
public disabled;
public ownerNode;
public parentStyleSheet;
public href;
public title;
public media;
function __construct( $type, $disabled, $ownerNode, $parentStyleSheet, $href, $title) <
$this->type = $type;
$this->disabled = $disabled;
$this->media = new MediaList();
$this->ownerNode = $ownerNode;
$this->parentStyleSheet = $parentStyleSheet;
$this->href = $href;
$this->title = $title;
>
>
?>
innerHTML in PHP DOM
function DOMinnerHTML ( $element )
<
$innerHTML = «» ;
$children = $element -> childNodes ;
foreach ( $children as $child )
<
$tmp_dom = new DOMDocument ();
$tmp_dom -> appendChild ( $tmp_dom -> importNode ( $child , true ));
$innerHTML .= trim ( $tmp_dom -> saveHTML ());
>
return $innerHTML ;
>
?>
Example:
= new DOMDocument ();
$dom -> load ( $html_string );
$dom -> preserveWhiteSpace = false ;
$domTable = $dom -> getElementsByTagName ( «table» );
foreach ( $domTable as $tables )
<
echo DOMinnerHTML ( $tables );
>
?>
If you want to print the DOM XML file content, you can use the next code:
$doc = new DOMDocument();
$doc->load($xmlFileName);
echo «
» . $doc->documentURI;
$x = $doc->documentElement;
getNodeContent($x->childNodes, 0);
function getNodeContent($nodes, $level) <
foreach ($nodes AS $item) <
// print «
TIPO: » . $item->nodeType ;
printValues($item, $level);
if ($item->nodeType == 1) < //DOMElement
foreach ($item->attributes AS $itemAtt) <
printValues($itemAtt, $level+3);
>
if($item->childNodes || $item->childNodes->lenth > 0) <
getNodeContent($item->childNodes, $level+5);
>
>
>
>
function printValues($item, $level) <
if ($item->nodeType == 1) < //DOMElement
printLevel($level);
print $item->nodeName . » = » . $item->nodeValue;
>
if ($item->nodeType == 2) < //DOMAttr
printLevel($level);
print $item->name . » = » . $item->value ;
>
if ($item->nodeType == 3) < //DOMText
if ($item->isWhitespaceInElementContent() == false) <
printLevel($level);
print $item->wholeText ;
>
>
>
function printLevel($level)
<
print «
«;
if ($level == 0) <
print «
«;
>
for($i=0; $i
I had problems with the dom2array_full function by «nospam at ya dot ru». Here’s my function, which works correctly for my project, and might work for yours:
function dom_to_array ( $root )
<
$result = array();
if ( $root -> hasAttributes ())
<
$attrs = $root -> attributes ;
foreach ( $attrs as $i => $attr )
$result [ $attr -> name ] = $attr -> value ;
>
$children = $root -> childNodes ;
if ( $children -> length == 1 )
<
$child = $children -> item ( 0 );
if ( $child -> nodeType == XML_TEXT_NODE )
<
$result [ ‘_value’ ] = $child -> nodeValue ;
if ( count ( $result ) == 1 )
return $result [ ‘_value’ ];
else
return $result ;
>
>
for( $i = 0 ; $i $children -> length ; $i ++)
<
$child = $children -> item ( $i );
if (!isset( $result [ $child -> nodeName ]))
$result [ $child -> nodeName ] = dom_to_array ( $child );
else
<
if (!isset( $group [ $child -> nodeName ]))
<
$tmp = $result [ $child -> nodeName ];
$result [ $child -> nodeName ] = array( $tmp );
$group [ $child -> nodeName ] = 1 ;
>
$result [ $child -> nodeName ][] = dom_to_array ( $child );
>
>
$xml= new DOMDocument();
$xml->preserveWhiteSpace=false;
$xml->loadXML($xmlDoc);
print_r(xml2array($xml));
A function among several others to parse a google results page, I wrote this some time ago — google has probably changed their site since then, but I thought this might be helpful to someone.
I’m moving servers, but I will probably throw this up on my blog when I get it back up.
function googleResult ( $listItem ) <
// given a LIST ITEM element, this will validate, and return an array for that LI entry as an inline result from google.
/*
*
*
*
* Description description
*
*
*
*
UPDATE:
This function will now look for any subcontainer that has an href, it doesn’t have to be an H3
this will make it work with a few more formatted search results.
*/
$listItem = $listItem -> childNodes ;
// Yes I don’t use instanceof — I guess you’ll have to deal.
foreach( $listItem as $element ) <
if( is_object ( $element ) && get_class ( $element ) == ‘DOMElement’ && $element -> hasChildNodes ()) <
$hrefContainer = $element -> childNodes ;
foreach( $hrefContainer as $element2 ) <
if( is_object ( $element2 ) && get_class ( $element2 ) == ‘DOMElement’ && $element2 -> nodeName == ‘a’ && $element2 -> hasAttribute ( ‘href’ )) <
$anchor = $element2 ;
unset( $h3 );
unset( $element2 );
break;
> else <
//print __LINE__ .» :: Breaking out of loop (normal result) element is not an annchor Element='».$element2->nodeName.»‘\n»;
>
>
unset( $element );
unset( $listItem );
break;
>
>
if(empty( $anchor ) || ! is_object ( $anchor ) || get_class ( $anchor ) != ‘DOMElement’ ) <
//print __LINE__ .» :: Returning false, did not locate anchor through iteration. «;
return false ;
>
$href = $anchor -> getAttribute ( ‘href’ );
if(empty( $href )) <
//print __LINE__ .» :: Found anchor object, could not read href attribute / href is empty? href=’$href’\n»;
return false ;
>
$description = $anchor -> childNodes ;
$urlDescription = » ;
foreach( $description as $words ) <
$name = trim ( $words -> nodeName );
if( $name == ’em’ || $name == ‘#text’ || $name == ‘b’ ) <
if(!empty( $words -> nodeValue )) <
$text = trim ( $words -> nodeValue );
$urlDescription = $urlDescription . $text . ‘ ‘ ;
>
>
>
$urlDescription = htmlspecialchars_decode ( $urlDescription , ENT_QUOTES );
$urlDescription = trim ( $urlDescription );
return array( ‘description’ => $urlDescription , ‘href’ => $href );
>
Источник