PHP Basics

DOMDocument::getElementById

Эта функция похожа на DOMDocument::getElementsByTagName, но ищет элемент с заданным идентификатором.

Для работы этой функции необходимо установить атрибуты идентификаторов с помощью DOMElement::setIdAttribute, либо DTD, который определяет атрибут идентификатора типа. В последнем случае перед использованием этой функции вам необходимо будет проверить документ с помощью DOMDocument::validate или DOMDocument::$validateOnParse.

Список параметров

Уникальный значение идентификатора элемента.

Возвращаемые значения

Возвращает объект DOMElement или null , если элемент не найден.

Примеры

Пример #1 Пример использования DOMDocument::getElementById()

Следующие примеры используют файл book.xml , который содержит следующие данные:

          ]>  Jim Smith Jane Smith PHP Basics provides an introduction to PHP.

]]>
Jon Doe

// Нужно проверить документ перед тем как ссылаться по идентификатору
$doc -> validateOnParse = true ;
$doc -> Load ( ‘book.xml’ );

echo «Элемент с идентификатором ‘php-basics’: » . $doc -> getElementById ( ‘php-basics’ )-> tagName . «\n» ;

Результат выполнения данного примера:

Элемент с идентификатором 'php-basics': book

Смотрите также

User Contributed Notes 10 notes

Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.

From my experience, getElementById seem to work fine without any setups if you have loaded a HTML document. But in order for getElementById to work with a simple XML document that you’ve «constructed», you have to set up the id with «xml:» prefix and use setIdAttribute on the element you created or it won’t work. See following example, hope this will save someone’s frustration. If you have loaded the xml file, then all you have to make sure is the ID has a xml: prefix for the attribute. But if you start to append the XML document, don’t forget to setIdAttribute on the id name or those elements or getElementById will return null when you try to find them.

$xmlDom = new DOMDocument ( ‘1.0’ , ‘utf-8’ );
$xmlDom -> formatOutput = true ; // we want a nice output

// create a root
$eltRoot = $xmlDom -> createElement ( «root» );
$xmlDom -> appendChild ( $eltRoot );

$eltChild = $xmlDom -> createElement ( «child» );
$eltRoot -> appendChild ( $eltChild );

// add a id attribute
$attr = $xmlDom -> createAttribute ( «xml:id» ); // needs xml prefix or getElementById won’t work
$eltChild -> appendChild ( $attr );

/// create the text node and append to the created element
$tNode = $xmlDom -> createTextNode ( «id_8120528» );
$attr -> appendChild ( $tNode );
$eltChild -> setIdAttribute ( «xml:id» , true ); // VERY IMPORT or getElementById won’t work

Читайте также:  Css display inline hover

// add a id attribute
$attr = $xmlDom -> createAttribute ( «status» );
$eltChild -> appendChild ( $attr );

/// create the text node and append to the created element
$tNode = $xmlDom -> createTextNode ( «partial» );
$attr -> appendChild ( $tNode );

// add a subchild
$eltSub = $xmlDom -> createElement ( «sub_child» );
$eltChild -> appendChild ( $eltSub );

$tNode = $xmlDom -> createTextNode ( «Some Data» );
$eltSub -> appendChild ( $tNode );

$id = null ;
$id = $xmlDom -> getElementById ( «id_8120528» );

$strId = $id -> getAttribute ( «xml:id» ); // bug? empty
$strStatus = $id -> getAttribute ( «status» ); // this works!

$xmlDom -> save ( «./_data/test.xml» );

$xmlDom -> load ( «./_data/test.xml» ); // reloading fixes the problem

$nodeRoot = $xmlDom -> getElementsByTagName ( «root» );
if ( $nodeRoot -> length > 0 ) $eltRoot = $nodeRoot -> item ( 0 );
>

$id = null ;
$id = $xmlDom -> getElementById ( «id_8120528» );

$strId = $id -> getAttribute ( «xml:id» ); // this works now!
$strStatus = $id -> getAttribute ( «status» ); // this works!

Источник

DOMDocument::getElementsByTagName

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

Parameters

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Return Values

A new DOMNodeList object containing all the matched elements.

Examples

Example #1 Basic Usage Example

$dom = new DOMDocument ;
$dom -> loadXML ( $xml );
$books = $dom -> getElementsByTagName ( ‘book’ );
foreach ( $books as $book ) echo $book -> nodeValue , PHP_EOL ;
>
?>

The above example will output:

Patterns of Enterprise Application Architecture Design Patterns: Elements of Reusable Software Design Clean Code

See Also

User Contributed Notes 14 notes

Return if there are no matches is an empty DOMNodeList. Check using length property, e.g.:

$nodes = $domDocument -> getElementsByTagName ( ‘book’ ) ;
if ( $nodes -> length == 0 ) <
// no results
>
?>

Note that when using getElementsByTagName that it is a dynamic list. Thus if you have code which adjusts the DOM structure it will change the results of the getElementsByTagName results list.

The following code iterates through a complete set of results and changes them all to a new tag:

$nodes = $xml -> getElementsByTagName ( «oldtag» );

$nodeListLength = $nodes -> length ; // this value will also change
for ( $i = 0 ; $i < $nodeListLength ; $i ++)
$node = $nodes -> item ( 0 );

// some code to change the tag name from «oldtag» to something else
// e.g. encrypting a tag element
>
?>

Since the list is dynamically updating, $nodes->item(0) is the next «unchanged» tag.

My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name ‘className’, then.

Читайте также:  Javascript определить количество строк

$some_link = ‘some website’ ;
$tagName = ‘div’ ;
$attrName = ‘class’ ;
$attrValue = ‘className’ ;

$dom = new DOMDocument ;
$dom -> preserveWhiteSpace = false ;
@ $dom -> loadHTMLFile ( $some_link );

$html = getTags ( $dom , $tagName , $attrName , $attrValue );
echo $html ;

function getTags ( $dom , $tagName , $attrName , $attrValue ) $html = » ;
$domxpath = new DOMXPath ( $dom );
$newDom = new DOMDocument ;
$newDom -> formatOutput = true ;

$filtered = $domxpath -> query ( «// $tagName » . ‘[@’ . $attrName . «=’ $attrValue ‘]» );
// $filtered = $domxpath->query(‘//div[@class=»className»]’);
// ‘//’ when you don’t know ‘absolute’ path

// since above returns DomNodeList Object
// I use following routine to convert it to string(html); copied it from someone’s post in this site. Thank you.
$i = 0 ;
while( $myItem = $filtered -> item ( $i ++) ) $node = $newDom -> importNode ( $myItem , true ); // import node
$newDom -> appendChild ( $node ); // append node
>
$html = $newDom -> saveHTML ();
return $html ;
>

?>

Please, improve it, and share it.

Following Example is of multiple attributes and multiple child nodes. this is being used to make joomla plugin for bulk upload of articles. Gurmukh Singh Bhatti

$dom = new DomDocument ;
$dom -> preserveWhiteSpace = FALSE ;
$dom -> loadXML ( $xml );
$params = $dom -> getElementsByTagName ( ‘section’ ); // Find Sections
$k = 0 ;
foreach ( $params as $param ) //go to each section 1 by 1
echo «Section Attribute :-> » . $params -> item ( $k )-> getAttribute ( ‘name’ ). «
» ; //get section attribute
$params2 = $params -> item ( $k )-> getElementsByTagName ( ‘category’ ); //digg categories with in Section
$i = 0 ; // values is used to iterate categories
foreach ( $params2 as $p ) echo »  — Category Attribute Name :-> » . $params2 -> item ( $i )-> getAttribute ( ‘name’ ). «
» ; //get Category attributes
$params3 = $params2 -> item ( $i )-> getElementsByTagName ( ‘arti’ ); //dig Arti into Categories
$j = 0 ; //values used to interate Arti
foreach ( $params3 as $p2 )
echo »   — Article Attribute Name : » . $params3 -> item ( $j )-> getAttribute ( ‘name’ ). «» ; //get arti atributes
echo »   Value : » . $params3 -> item ( $j )-> nodeValue . «
» ; //get Node value ;
$j ++;
>
$i ++;
>
$k ++;

>
?>

output :
Section Attribute :-> Section1
— Category Attribute Name :-> google
— Article Attribute Name : article1 Value : any html code heremy name is so so
— Article Attribute Name : article2 Value : value2
— Article Attribute Name : article3 Value : value3
— Article Attribute Name : article4 Value : value4
— Category Attribute Name :-> yahoo
— Article Attribute Name : articleSection2 Value : Test value
Section Attribute :-> Section2
— Category Attribute Name :-> msn
— Article Attribute Name : article2 Value : value1
— Article Attribute Name : article3 Value : value2
— Category Attribute Name :-> webcare
— Article Attribute Name : param3 Value : value4

Читайте также:  Define empty string php

Here is an example of getElementsByTagName():

$dom = new DomDocument ;
$dom -> preserveWhiteSpace = FALSE ;
$dom -> loadXML ( $xml );
$params = $dom -> getElementsByTagName ( ‘param’ );

foreach ( $params as $param ) echo $param -> getAttribute ( ‘name’ ). ‘
‘ ;
>
?>

Expected result:
—————
param1
param2
param3

This is a very simplistic way to traverse xml nodes and childnodes using the DOMDocument class

I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.

Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.

When using getElementsByTagName, the new nodes are «added» to the nodelist i already am looping through.

When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.

I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.

class SmartDocument extends DOMDocument private $localDom ;
public $xpath ;
private $serialize = array( ‘localDom’ );

private $elemName ;
private $elemCounter ;

/**
* Constructor
*/
function __construct () parent :: __construct ( ‘1.0’ , ‘UTF-8’ );
$this -> preserveWhiteSpace = false ;
$this -> recover = TRUE ;
$this -> xpath = new DOMXpath ( $this );
>

/**
* GetElementsByTagname within an contextNode
*
* @param string $name
* @param DomNode $contextNode
* @return DOMNode|NULL
*/
public function getElementsByTagNameContext ( $name , $contextNode )

if( $this -> elemName != $name ) $this -> elemCounter = 0 ;
$this -> elemName = $name ;
>

$this -> elemLength = $this -> xpath -> evaluate ( ‘count(.//*[name() keyword»>. $this -> elemName . ‘»])’ , $contextNode );
while( $this -> elemCounter < $this ->elemLength ) $this -> elemCounter ++;
$nl = $this -> xpath -> query ( ‘.//*[name() keyword»>. $this -> elemName . ‘»][‘ . $this -> elemCounter . ‘]’ , $contextNode );
if( $nl -> length == 1 ) return $nl -> item ( 0 );
>
>

$this -> elemLength = null ;
$this -> elemCounter = null ;
$this -> elemName = null ;
return null ;
>
>

$doc = new SmartDocument ();
$doc -> load ( ‘book.xml’ );

$nl = $doc -> query ( ‘//books’ );
foreach( $nl as $node ) while( $book = $doc -> getElementsByTagNameContext ( ‘book’ , $node )) //When you now create new nodes within this loop as child or following-sibling of this node
// They show up within this loop
>

Источник

Оцените статью