文字

The DOMElement class

(PHP 5, PHP 7)

类摘要

DOMElement extends DOMNode {
readonly public bool $schemaTypeInfo ;
readonly public string $tagName ;
public __construct ( string $name [, string $value [, string $namespaceURI ]] )
public string getAttribute ( string $name )
public DOMAttr getAttributeNode ( string $name )
public DOMAttr getAttributeNodeNS ( string $namespaceURI , string $localName )
public string getAttributeNS ( string $namespaceURI , string $localName )
public DOMNodeList getElementsByTagName ( string $name )
public DOMNodeList getElementsByTagNameNS ( string $namespaceURI , string $localName )
public bool hasAttribute ( string $name )
public bool hasAttributeNS ( string $namespaceURI , string $localName )
public bool removeAttribute ( string $name )
public bool removeAttributeNode ( DOMAttr $oldnode )
public bool removeAttributeNS ( string $namespaceURI , string $localName )
public DOMAttr setAttribute ( string $name , string $value )
public DOMAttr setAttributeNode ( DOMAttr $attr )
public DOMAttr setAttributeNodeNS ( DOMAttr $attr )
public void setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value )
public void setIdAttribute ( string $name , bool $isId )
public void setIdAttributeNode ( DOMAttr $attr , bool $isId )
public void setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId )
public DOMNode DOMNode::appendChild ( DOMNode $newnode )
public string DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public int DOMNode::C14NFile ( string $uri [, bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] )
public DOMNode DOMNode::cloneNode ([ bool $deep ] )
public int DOMNode::getLineNo ( void )
public string DOMNode::getNodePath ( void )
public bool DOMNode::hasAttributes ( void )
public bool DOMNode::hasChildNodes ( void )
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
public bool DOMNode::isDefaultNamespace ( string $namespaceURI )
public bool DOMNode::isSameNode ( DOMNode $node )
public bool DOMNode::isSupported ( string $feature , string $version )
public string DOMNode::lookupNamespaceURI ( string $prefix )
public string DOMNode::lookupPrefix ( string $namespaceURI )
public void DOMNode::normalize ( void )
public DOMNode DOMNode::removeChild ( DOMNode $oldnode )
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
}

属性

schemaTypeInfo

Not implemented yet, always return NULL

tagName

The element name

注释

Note:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or Iconv for other encodings.

Table of Contents

  • DOMElement::__construct — Creates a new DOMElement object
  • DOMElement::getAttribute — Returns value of attribute
  • DOMElement::getAttributeNode — Returns attribute node
  • DOMElement::getAttributeNodeNS — Returns attribute node
  • DOMElement::getAttributeNS — Returns value of attribute
  • DOMElement::getElementsByTagName — Gets elements by tagname
  • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
  • DOMElement::hasAttribute — Checks to see if attribute exists
  • DOMElement::hasAttributeNS — Checks to see if attribute exists
  • DOMElement::removeAttribute — Removes attribute
  • DOMElement::removeAttributeNode — Removes attribute
  • DOMElement::removeAttributeNS — Removes attribute
  • DOMElement::setAttribute — Adds new attribute
  • DOMElement::setAttributeNode — Adds new attribute node to element
  • DOMElement::setAttributeNodeNS — Adds new attribute node to element
  • DOMElement::setAttributeNS — Adds new attribute
  • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

用户评论:

[#1] johnny [2014-03-03 15:48:39]

Get html of a node
 $html .= $dom->saveHTML($node);

[#2] Janne Enberg [2013-11-07 11:02:33]

This page doesn't list the inherited properties from DOMNode, e.g. the quite important textContent property. It would be immensely helpful if it would list those as well.

[#3] felix dot klee at inka dot de [2013-02-26 15:23:08]

How to rename an element and preserve attributes:

<?php

// 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 
'<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument'1.0' );
$d->loadXML('<?xml version="1.0"?>

<library>
  <data a:foo="1" x="bar" xmlns:a="http://example.com/a">
    <invite>
      <username>jmansa</username>
      <userid>1</userid>
    </invite>
    <update>1</update>
  </data>
</library>');

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if ($elements->length == 1) {
  $element = $elements->item(0);
  renameElement($element, 'invites');
}

prettyPrint($d);

?>

[#4] loopduplicate at burningtoken dot com [2011-04-22 02:34:05]

This works perfect for me as well:

<?php $xml $domElement->ownerDocument->saveXML($domElement); ?>

[#5] Anonymous [2010-12-24 08:22:23]

you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue

[#6] dpetroff ( at ) gmail.com [2010-12-04 23:24:44]

Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html$node ) {
    
$innerHTML'';
    
$children $node->childNodes;
    foreach (
$children as $child) {
        
$innerHTML .= $child->ownerDocument->saveXML$child );
    }

    return 
$innerHTML;
}
?>

[#7] nawaman at gmail dot com [2009-09-03 20:08:11]

The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node$Text "") {
    if (
$Node->tagName == null)
        return 
$Text.$Node->textContent;

    
$Node $Node->firstChild;
    if (
$Node != null)
        
$Text getTextFromNode($Node$Text);

    while(
$Node->nextSibling != null) {
        
$Text getTextFromNode($Node->nextSibling$Text);
        
$Node $Node->nextSibling;
    }
    return 
$Text;
}

function 
getTextFromDocument($DOMDoc) {
    return 
getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo 
getTextFromDocument($Doc)."\n";
?>

[#8] Daniel Morlock [2009-05-07 09:22:28]

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:

<?php
function getInnerHTML($Node)
{
     
$Body $Node->ownerDocument->documentElement->firstChild->firstChild;
     
$Document = new DOMDocument();     
     
$Document->appendChild($Document->importNode($Body,true));
     return 
$Document->saveHTML();
}
?>

[#9] patrick smith [2008-11-04 08:14:12]

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):

<?php
$innerHTML 
'';
$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();
}
?>

[#10] Pinochet [2008-10-25 05:33:34]

Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php 
echo $domElement->nodeValue
?>

Everything is obvious if you now about this thing ;-)

[#11] j DOT wagner ( AT ) medieninnovation.com [2008-10-08 09:11:51]

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.

[#12] Severin [2008-09-14 06:18:21]

I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom
->load($xmlFile))

$xpathQuery '/

?>

参见

  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace

用户评论:

[#1] Fabian dot Blech at gmx dot de [2010-07-22 08:30:57]

Remember, Dom-Nodes mustn't start with a number:

allowed:
<t12345t4>Value</t12345t4>

Not allowed:
<12345t4>VALUE</12345t4>

[#2] troelskn at gmail dot com [2008-06-03 07:46:22]

Note that this function is buggy. You have to manually escape the $value argument with htmlspecialchars.
See: http://bugs.php.net/bug.php?id=31191

[#3] adar at darkpoetry dot de [2007-05-07 13:27:09]

If you like to view an element simply do:

<?php
echo htmlentities($element->C14N());
?>


Undocumented but found ;)

上一篇: 下一篇: