Document Object Model
- Введение
- Установка и настройка
- Требования
- Установка
- Настройка во время выполнения
- Типы ресурсов
- Предопределенные константы
- DOMAttr — Класс DOMAttr
- DOMAttr::__construct — Создает экземпляр класса DOMAttr
- DOMAttr::isId — Проверяет, является ли атрибут описанным в DTD ID
- DOMCdataSection — Класс DOMCdataSection
- DOMCdataSection::__construct — Создает новый экземпляр класса DOMCdataSection
- DOMCharacterData — Класс DOMCharacterData
- DOMCharacterData::appendData — Добавляет строку в конец символьных данных узла
- DOMCharacterData::deleteData — Удаление диапазона символов из узла
- DOMCharacterData::insertData — Вставляет строку после заданного отступа из 16-битных блоков
- DOMCharacterData::replaceData — Заменяет подстроку в узле типа DOMCharacterData
- DOMCharacterData::substringData — Извлекает определенный диапазон данных из узла
- DOMComment — Класс DOMComment
- DOMComment::__construct — Создает новый экземпляр класса DOMComment
- DOMDocument — Класс DOMDocument
- DOMDocument::__construct — Создание нового DOMDocument объекта
- DOMDocument::createAttribute — Создает новый атрибут
- DOMDocument::createAttributeNS — Создает новый узел-атрибут с соответствующим ему пространством имен
- DOMDocument::createCDATASection — Создает новый cdata узел
- DOMDocument::createComment — Создает новый узел-комментарий
- DOMDocument::createDocumentFragment — Создание фрагмента докуента
- DOMDocument::createElement — Создает новый узел-элемент
- DOMDocument::createElementNS — Создание нового узла-элемента с соответствующим пространством имен
- DOMDocument::createEntityReference — Создание нового узла-ссылки на сущность
- DOMDocument::createProcessingInstruction — Создает новый PI-узел
- DOMDocument::createTextNode — Создает новый текстовый узел
- DOMDocument::getElementById — Ищет элемент с заданным id
- DOMDocument::getElementsByTagName — Ищет все элементы с заданным локальным именем
- DOMDocument::getElementsByTagNameNS — Ищет элементы с заданным именем в определенном пространстве имен
- DOMDocument::importNode — Импорт узла в текущий документ
- DOMDocument::load — Загрузка XML из файла
- DOMDocument::loadHTML — Загрузка HTML из строки
- DOMDocument::loadHTMLFile — Загрузка HTML из файла
- DOMDocument::loadXML — Загрузка XML из строки
- DOMDocument::normalizeDocument — Нормализует документ
- DOMDocument::registerNodeClass — Регистрация расширенного класса, используемого для создания базового типа узлов
- DOMDocument::relaxNGValidate — Производит проверку документа на правильность построения посредством relaxNG
- DOMDocument::relaxNGValidateSource — Проверяет документ посредством relaxNG
- DOMDocument::save — Сохраняет XML дерево из внутреннего представления в файл
- DOMDocument::saveHTML — Сохраняет документ из внутреннего представления в строку, используя HTML форматирование
- DOMDocument::saveHTMLFile — Сохраняет документ из внутреннего представления в файл, используя HTML форматирование
- DOMDocument::saveXML — Сохраняет XML дерево из внутреннего представления в виде строки
- DOMDocument::schemaValidate — Проверяет действительности документа, основываясь на заданной схеме
- DOMDocument::schemaValidateSource — Проверяет действительность документа, основываясь на схеме
- DOMDocument::validate — Проверяет документ на соответствие его DTD
- DOMDocument::xinclude — Проводит вставку XInclude разделов в объектах DOMDocument
- DOMDocumentFragment — Класс DOMDocumentFragment
- DOMDocumentFragment::appendXML — Добавление необработанных XML данных
- DOMDocumentType — Класс DOMDocumentType
- DOMElement — Класс DOMElement
- 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 пространства имен идентифицирующим
- DOMEntity — Класс DOMEntity
- DOMEntityReference — Класс DOMEntityReference
- DOMEntityReference::__construct — Создает новый объект класса DOMEntityReference
- DOMException — Класс DOMException
- DOMImplementation — Класс DOMImplementation
- DOMImplementation::__construct — Создает новый объект класса DOMImplementation
- DOMImplementation::createDocument — Создает объект класса DOMDocument заданного типа с элементом document
- DOMImplementation::createDocumentType — Создает пустой объект класса DOMDocumentType
- DOMImplementation::hasFeature — Тестирует реализацию специфичных возможностей объекта DOMImplementation
- DOMNamedNodeMap — Класс DOMNamedNodeMap
- DOMNamedNodeMap::getNamedItem — Извлекает узел с заданным именем
- DOMNamedNodeMap::getNamedItemNS — Извлекает узел с заданным локальным именем и URI пространства имен
- DOMNamedNodeMap::item — Извлекает узел с заданным индексом
- DOMNode — Класс DOMNode
- DOMNode::appendChild — Добавляет новый дочерний узел в конец списка потомков
- DOMNode::C14N — Canonicalize nodes to a string
- DOMNode::C14NFile — Canonicalize nodes to a file
- DOMNode::cloneNode — Клонирует узел
- DOMNode::getLineNo — Возвращает номер строки узла
- DOMNode::getNodePath — Получение XPath пути к узлу
- DOMNode::hasAttributes — Проверяет, содержит ли данный узел атрибуты
- DOMNode::hasChildNodes — Проверяет, содержит ли данный узел потомков
- DOMNode::insertBefore — Добавляет новый дочерний узел перед опорным узлом
- DOMNode::isDefaultNamespace — Проверяет, совпадает ли URI пространства имен узла с пространством имен по умолчанию
- DOMNode::isSameNode — Проверяет, являются ли два узла одним и тем же узлом
- DOMNode::isSupported — Проверяет, поддерживается ли заданное свойство в определенной версии
- DOMNode::lookupNamespaceURI — Получает URI пространства имен узла по префиксу
- DOMNode::lookupPrefix — Возвращает префикс пространства имен узла из URI пространства имен
- DOMNode::normalize — Нормализует узел
- DOMNode::removeChild — Удаляет дочерний узел из списка потомков
- DOMNode::replaceChild — Заменяет дочерний узел
- DOMNodeList — Класс DOMNodeList
- DOMNodelist::item — Извлекает узел с заданным индексом
- DOMNotation — Класс DOMNotation
- DOMProcessingInstruction — Класс DOMProcessingInstruction
- DOMProcessingInstruction::__construct — Создает новый объект классаDOMProcessingInstruction
- DOMText — The DOMText class
- DOMText::__construct — Создает объект класса DOMText
- DOMText::isWhitespaceInElementContent — Определяет, содержит ли текстовый узел пробел в содержимом
- DOMText::splitText — Разделяет узел на два, начиная с заданной позиции
- DOMXPath — Класс DOMXPath
- DOMXPath::__construct — Создает новый объект класса DOMXPath
- DOMXPath::evaluate — Вычисляет переданное XPath выражение и возвращает типизированный результат, если возможно
- DOMXPath::query — Выполняет заданное XPath выражение
- DOMXPath::registerNamespace — Ассоциирует пространство имен с объектом DOMXPath
- DOMXPath::registerPhpFunctions — Регистрация функций PHP как XPath функций
- DOM Функции
- dom_import_simplexml — Получает объект класса DOMElement из объекта класса SimpleXMLElement
User Contributed Notes 41 notes
2
tobiasz.cudnik[at]gmail.com ¶5 years ago
// just one file to include
require('phpQuery/phpQuery.php');
$html = '
<div>
mydiv
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>';
// 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();
2
Drupella ¶2 years ago
function innerHTML($el) {
$doc = new DOMDocument();
$doc->appendChild($doc->importNode($el, TRUE));
$html = trim($doc->saveHTML());
$tag = $el->nodeName;
return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
}
0
miguelangelhdz at NOSPAM dot com ¶5 years ago
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)."<br/>";
echo get_class($doc->documentElement)."<br/>";
echo "<xmp>".$doc->saveXML()."</xmp>";
0
Sven Arduwie ¶5 years ago
function xml2array($xml) {
$domDocument = new DOMDocument;
$domDocument->loadXML($xml);
$domXPath = new DOMXPath($domDocument);
$array = array();
foreach ($domXPath->query('//key') as $keyDOM) {
$id = $keyDOM->getAttribute('id');
$value = $keyDOM->hasAttribute('value') ? $keyDOM->getAttribute('value') : trim($keyDOM->textContent);
if (array_key_exists($id, $array)) {
if (is_array($array[$id])) {
$array[$id][] = $value;
} else {
$array[$id] = array($array[$id]);
$array[$id][] = $value;
}
} else {
$array[$id] = $value;
}
}
return $array;
}
0
danf dot 1979 at []gmail[] dot com ¶5 years ago
// XML data
$xml_string = "<?xml version='1.0'
0
moshedolev at gmail dot com ¶5 years ago
function AtoX($array, $DOM=null, $root=null){
if($DOM == null){$DOM = new DOMDocument('1.0', 'iso-8859-1');}
if($root == null){$root = $DOM->appendChild($DOM->createElement('root'));}
$name = $array['#MULTIPLE_ELEMENT_NAME'];
foreach($array as $key => $value){
if(is_int($key) && $name != null){
if(is_array($value)){
$subroot = $root->appendChild($DOM->createElement($name));
AtoX($value, $DOM, $subroot);
}
else if(is_scalar($value)){
$root->appendChild($DOM->createElement($name, $value));
}
}
else if(is_string($key) && $key != '#MULTIPLE_ELEMENT_NAME'){
if(is_array($value)){
$subroot = $root->appendChild($DOM->createElement($key));
AtoX($value, $DOM, $subroot);
}
else if(is_scalar($value)){
$root->appendChild($DOM->createElement($key, $value));
}
}
}
return $DOM;
}
$array = array(
'#MULTIPLE_ELEMENT_NAME' => 'GenericDatas',
'Date' => 'November 03, 2007',
'Company' => 'Facility One',
'Field' => 'Facility Management Software',
'Employees' => array(
'#MULTIPLE_ELEMENT_NAME' => 'Employee',
'Cindy',
'Sean',
'Joe',
'Owen',
'Jim',
'Dale',
'Kelly',
'Ryan',
'Johnathan',
'Robin',
'William Marcus',
'NewCoops' => array(
'#MULTIPLE_ELEMENT_NAME' => 'Coop',
'John',
'Tyler',
'Ray',
'Dawn'
)
),
'Datas',
'DATAS',
'OtherDatas'
);
$DOM = new DOMDocument('1.0', 'iso-8859-1');
$root = $DOM->appendChild($DOM->createElement('CompanyData'));
$DOM = AtoX($array, $DOM, $root);
$DOM->save('C:\test.xml');
0
freyjkell at gmail dot com ¶6 years ago
$dom=new DOMDocument();
$dom->load('file.xhtml',LIBXML_DTDLOAD); // NOT resolveExternals - it needs true doctype, and includes crap code
// some DOM operations
$doctype=DOMImplementation::createDocumentType("html","-//W3C//DTD XHTML 1.1//EN","http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"); // creating real doctype
$output=DOMImplementation::createDocument('','',$doctype);
$output->appendChild($output->importNode($dom->documentElement,true));
$output->encoding='utf-8';
$output=$output->saveXML();
$xhtml=preg_match(
'/application\/xhtml\+xml(?![+a-z])'.
'(;q=(0\.\d{1,3}|[01]))?/i',
$_SERVER['HTTP_ACCEPT'],$xhtml) &&
(isset($xhtml[2])?$xhtml[2]:1) > 0 ||
strpos($_SERVER["HTTP_USER_AGENT"],
"W3C_Validator")!==false ||
strpos($_SERVER["HTTP_USER_AGENT"],
"WebKit")!==false; // XHTML Content-Negotiation
header('Content-Type: '.($xhtml?'application/xhtml+xml':'text/html').'; charset=utf-8');
print $output;
0
PHPdeveloper ¶6 years ago
function parseStyleSheetfor Email($html)
{
$doc = new DOMDocument;
$doc->loadHTML($html);
// grab inline stylesheet as DOM object
$oStyle = $doc->getElementsByTagName('style')->item(0);
// grab rule identifiers and rules
preg_match_all('/^([-#._a-z0-9]+) ?\{(.*?)\}/ims', $oStyle->nodeValue, $aMatches, PREG_SET_ORDER);
foreach ($aMatches as $aRule) {
$rule_id = $aRule[1];
// clean up rules
$rule = str_replace(array("\r", "\n", ' ', '; '), array('', '', ' ', ';'), $aRule[2]);
$rule = preg_replace(array('/^ /', '/;$/'), '', $rule);
// generic rules
if (!strstr($rule_id, '.') && !strstr($rule_id, '#')) {
$items = $doc->getElementsByTagName($rule_id);
// set style attribute equal to rule from stylesheet
foreach ($items as $item) {
// if there is already inline style append it to end of stylesheet rule
$current_style = $item->getAttribute('style');
if (!empty($current_style)) {
$item->setAttribute('style', $rule . ';' . $current_style);
} else {
$item->setAttribute('style', $rule);
}
}
// classes
} elseif (strstr($rule_id, '.')) {
list($rule_tag, $rule_class) = explode('.', $rule_id);
$items = $doc->getElementsByTagName($rule_tag);
foreach ($items as $item) {
$class = $item->getAttribute('class');
if ($class == $rule_class) {
// if there is already inline style append it to end of stylesheet rule
$current_style = $item->getAttribute('style');
if (!empty($current_style)) {
$item->setAttribute('style', $current_style . ';' . $rule);
} else {
$item->setAttribute('style', $rule);
}
// remove class as it won't be used now
$item->removeAttribute('class');
}
}
// ids
} elseif (strstr($rule_id, '#')) {
list($rule_tag, $id) = explode('#', $rule_id);
$item = $doc->getElementById($id);
$current_style = $item->getAttribute('style');
if (!empty($current_style)) {
$item->setAttribute('style', $current_style . ';' . $rule);
} else {
$item->setAttribute('style', $rule);
}
// remove class as it won't be used now
$item->removeAttribute('id');
}
}
// remove inline stylesheet
$oStyle->parentNode->removeChild($oStyle);
return $doc->saveHTML();
}
0
sean at lookin3d dot com ¶7 years ago
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( "" );
}
}
0
johanwthijs-at-hotmail-dot-com ¶7 years ago
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.
/*
* <li class='g w0'>
* <h3 class='r'>
* <a href='the URL' class='l'>
* Description <em>description</em>
* </a>
* </h3>
* </li>
*
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);
}
-1
odessa131 at aol dot nospam dot com ¶4 years ago
I had the hardest time updating a complex XML document. Here's a quick example on how to do it.
<?php
// Load the XML from a file.
$xml = "a2062.xml"; // This is an XFDL form previously unencoded and ungzipped.
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->Load($xml);
// Create an XPath query.
// Note: you must define the namespace if the XML document has defined namespaces.
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xfdl', "http://www.PureEdge.com/XFDL/6.5");
// Locate the value for the first Item Description field.
$query = "//xfdl:page/xfdl:field[@sid='ITEMDESA']/xfdl:value";
$nodeList = $xpath->query($query);
$nodeList->item(0)->nodeValue = "This is the text in the value node of the first Item Description field inside the DA 2062 PureEdge form.";
$dom->save($xml);
-1
philipwaynerollins at gmail dot com ¶4 years ago
$doc = new DOMDocument( );
$ele = $doc->createElement( 'p', 'Sensei Ninja' );
print $ele->nodeValue;
-1
Junior ¶4 years ago
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;
}
-1
nospam at ya dot ru ¶4 years ago
function dom2array_full($node){
$result = array();
if($node->nodeType == XML_TEXT_NODE) {
$result = $node->nodeValue;
}
else {
if($node->hasAttributes()) {
$attributes = $node->attributes;
if(!is_null($attributes))
foreach ($attributes as $index=>$attr)
$result[$attr->name] = $attr->value;
}
if($node->hasChildNodes()){
$children = $node->childNodes;
for($i=0;$i<$children->length;$i++) {
$child = $children->item($i);
if($child->nodeName != '#text')
if(!isset($result[$child->nodeName]))
$result[$child->nodeName] = dom2array($child);
else {
$aux = $result[$child->nodeName];
$result[$child->nodeName] = array( $aux );
$result[$child->nodeName][] = dom2array($child);
}
}
}
}
return $result;
}
-1
cgorbit spamless_at ya dot ru ¶5 years ago
function gaie( $node, &$arr, $attr )
{
if ( $value = $node->getAttribute( $attr ) )
$arr[ $attr ] = u2w( $value );
}
function innerXML( $l, $collapse_all = true, $top_run = true )
{
$atts4elements = array(
'a' => 'href',
'table' => 'border,cellpadding,cellspacing',
'td' => 'colspan,rowspan'
);
$s = '';
if ( $top_run ) :
ob_start();
-1
Anonymous ¶5 years ago
class MyElement extends DOMElement{
public $myProp="myProp";
public function myMethod(){
return 'myMethod()';
}
}
$myDocument=new DOMDocument();
$myDocument->appendChild(new MyElement('myElement','myElement'));
echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
-1
sweisman at pobox dot com ¶4 years ago
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;
}
}
$group = array();
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);
}
}
return $result;
}
-1
trollboy at shoggoth dot net ¶6 years ago
/**
* basic class for converting an array to xml.
* @author Matt Wiseman (trollboy at shoggoth.net)
*
*/
class array2xml {
public $data;
public $dom_tree;
/**
* basic constructor
*
* @param array $array
*/
public function __construct($array){
if(!is_array($array)){
throw new Exception('array2xml requires an array', 1);
unset($this);
}
if(!count($array)){
throw new Exception('array is empty', 2);
unset($this);
}
$this->data = new DOMDocument('1.0');
$this->dom_tree = $this->data->createElement('result');
$this->data->appendChild($this->dom_tree);
$this->recurse_node($array, $this->dom_tree);
}
/**
* recurse a nested array and return dom back
*
* @param array $data
* @param dom element $obj
*/
private function recurse_node($data, $obj){
$i = 0;
foreach($data as $key=>$value){
if(is_array($value)){
//recurse if neccisary
$sub_obj[$i] = $this->data->createElement($key);
$obj->appendChild($sub_obj[$i]);
$this->recurse_node($value, $sub_obj[$i]);
} elseif(is_object($value)) {
//no object support so just say what it is
$sub_obj[$i] = $this->data->createElement($key, 'Object: "' . $key . '" type: "' . get_class($value) . '"');
$obj->appendChild($sub_obj[$i]);
} else {
//straight up data, no weirdness
$sub_obj[$i] = $this->data->createElement($key, $value);
$obj->appendChild($sub_obj[$i]);
}
$i++;
}
}
/**
* get the finished xml
*
* @return string
*/
public function saveXML(){
return $this->data->saveXML();
}
}
$test = array(
'cat'=>'animal',
'container'=> array(
'thing'=>'stuff',
'thing2'=>'stuff2',
'thing3'=>3,
'thing4'=>4,
'wtf'=> new stdClass(),
),
'foo'=>'bar',
);
var_dump($test);
try {
$o_test = new array2xml($test);
} catch (Exception $e) {
echo $e->getMessage();
}
echo $o_test->saveXML();
-2
fantasyman3000 at gmail dot com ¶5 years ago
/**
* result sample : /html[1]/body[1]/span[1]/fieldset[1]/div[1]
* @return string
*/
function getNodeXPath( $node ) {
$result='';
while ($parentNode = $node->parentNode) {
$nodeIndex=-1;
$nodeTagIndex=0;
do {
$nodeIndex++;
$testNode = $parentNode->childNodes->item( $nodeIndex );
if ($testNode->nodeName==$node->nodeName and $testNode->parentNode->isSameNode($node->parentNode) and $testNode->childNodes->length>0) {
//echo "{$testNode->parentNode->nodeName}-{$testNode->nodeName}-{}<br/>";
$nodeTagIndex++;
}
} while (!$node->isSameNode($testNode));
$result="/{$node->nodeName}[{$nodeTagIndex}]".$result;
$node=$parentNode;
};
return $result;
}
Смотрите также:
Описание на ru2.php.net
Описание на php.ru