Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Olá Galerinha ..
Há alguns dias atras, prescisei lidar com XML
Então escrevi uma classe para manipular o XML, ou HTML .. alterando, removendo, gravando
Dados nesse Arquivo, Então apos terminei oque eu presisava fazer, resolvi compartilhar
a classe, caso algum dia alguem presise fazer feed, ou integrar a NF-e seu sistema em PHP
a classe pode ajudar, Deixei documentado cada metodo da classe e uma pasta com Exemplos
Trabalhando Com JSON, XML .. Entre outras coisas que a class faz, e Tambem a documentação gerada
Pelo Doxygen \ PHPDoc Está em 2 Arquivos Index na Pasta Raiz, Qualquer Duvida Pode Postar Aqui
Oque Estiver ao Meu Alcançe Tentarei Resolver ;) , Vou dar Algumas Atualizaçoes claro, melhorando o desempenho
e algumas coisas que sei que posso melhorar ^_^
Então o Codigo Completo Abaixo da Classe
<?php
/**
* Classe Document
* Construida para Simples Manipulação de Arquivos XML, HTML
* No Qual Permite Você Manipular Todos Seus Dados
* De Uma Maneira Facil e Flexivel, Por Isso o Uso da Fluent Interface
* Já Que a Maioria dos Retornos dos Metodos Não Aceitam em Si
* Sua Formatação Pra String, O Fluent Interface Pode Ser Usado
* Normalmente em Cada Metodo Que Tem Proximos Metodos a Serem
* Chamados Durante o Uso
*
* @author Andrey Knupp Vital
* @copyright (C) 2011 - 2012im
* @package Document
* @version 1.1.0
* @since 1.0.0
* @access Public
*
* @tutorial http://www.php.net/manual/en/class.domattr.php
* @tutorial http://www.php.net/manual/en/class.domdocument.php
* @tutorial http://www.php.net/manual/en/class.domxpath.php
* @tutorial http://www.php.net/manual/en/class.domelement.php
* @tutorial http://www.php.net/manual/en/class.domexception.php
* @tutorial http://www.php.net/manual/en/class.domnamednodemap.php
* @tutorial http://www.php.net/manual/en/class.domnode.php
* @tutorial http://www.php.net/manual/en/class.domnodelist.php
* @tutorial http://www.php.net/manual/en/class.domtext.php
*/
final class Document{
/**
* Armazena a Instancia da Classe DOMDocument
* @access Public
* @var Object $DOMDocument
*/
public $DOMDocument;
/**
* Armazena a Instancia da Classe DOMXPath
* @access Public
* @var Object $DOMXPath
*/
public $DOMXPath;
/**
* Armazena o Local Que o Documento Foi Carregado
* @access Private
* @var String $Path
*/
private $Path;
/**
* Armazena o Elemento Que foi Anexado No Documento
* @access Public
* @var String $appendedElement
*/
public $appendedElement;
/**
* Armazena o Array dos Resultados Do Metodo Query
* @acces Public
* @var Array $result
*/
public $result;
/**
* Armazena a Query do DOMXPath
* @access Protected
* @var String $setQuery
*/
protected $setQuery;
/**
* Armazena a Instancia do Banco de Dados
* Objeto do PDO
* @access Public
* @var Object $DBHandler
*/
public $DBHandler;
/**
* Armazena o Elemento Raiz do Documento
* Carregado Atraves do Metodo Load
* @access Private
* @var String $DOCRootElement
*/
private $DOCRootElement;
/**
* Armazena a Query Do DOMXPath
* @access Public
* @var String $Query
*/
public $Query;
/**
* Armazena o Nome de um Elemento Criado
* @access Private
* @var String $ElementName
*/
private $ElementName;
/**
* Armazena o Nome de um Elemento Criado
* Pelo Metodo ->createElement
* No Qual Faz o Tratamento da String Removendo Tags HTML, E Aspas Simples '
* @access Private
* @var String $ElementName
*/
private $ElementNodeName;
/**
* Construtor da Classe
* Faz uma Nova Instancia do DOMDocument
* Setando Para a Classe, Uma Versão e Charset do Documento
* @param String $version
* @param String $charset
*/
public function __construct( $version = '1.0', $charset = 'iso-8859-1' ){
$this->DOMDocument = new DOMDocument( $version, $charset );
}
/**
* Faz uma Nova Instancia da Classe
* DOMXPath Usado Para Localizar Elementos no Documento
* Se Não Quiser Invocar Esse Metodo, Basta Setar o Segundo Parametro
* Do Metodo Load Como True, Isso vai Fazer Com Que a Classe DOMXPath
* Seje Inicializada Apos o Documento Ser Carregado
* @method xPath
* @return Document
*/
public function xPath(){
if( $this->DOMDocument instanceOf DOMDocument ){
$this->DOMXPath = new DOMXPath( $this->DOMDocument );
}
return $this;
}
/**
* Carrega o Documento Para Modificaçoes
* Esse Metodo e Neccessario Para Uso De Todos os Outros
* A Maioria Dos Outros Metodos dessa Classe Dependem do Documento
* Carregado Para Interação a Ele, Sem o Documento Carregado
* Atraves Desse Metodo, a Maioria Das Funçoes
* Não Teram Funcionamento Adequado Para Uso
* @method load
* @param String $Path
* @param Boolean $LoadXPath
* @return Document
*/
public function load( $Path, $LoadXPath = false ){
$this->Path = sprintf( '%s', $Path );
$this->DOMDocument->preserveWhiteSpace = false;
$this->DOMDocument->formatOutput = true;
if( !file_exists( $this->Path ) ){
throw new OutOfBoundsException( sprintf( 'O Arquivo %s Não Existe, Não Foi Possivel Carregar', $this->Path ) );
}
$this->DOMDocument->load( $this->Path );
if( $LoadXPath != false && $LoadXPath == true ){
if( $this->DOMDocument instanceOf DOMDocument ){
$this->DOMXPath = new DOMXPath( $this->DOMDocument );
}
}
return $this;
}
/**
* Faz uma Consulta no Documento Carregado
* Trazendo um Array Com Os Elementos e Seus Respectivos Valores
* @method query
* @param String $Query
* @param String $UnsetFields
* @return Array $this->result
*/
public function query( $Query, $UnsetFields = NULL ){
if( $Query == NULL || empty( $Query ) ):
throw new Exception( 'Sua Query Não Deve Estar Vazia !' );
endif;
$this->result = Array();
foreach( $this->DOMXPath->query( $Query ) as $this->values ){
$this->item = Array();
foreach( $this->values->childNodes as $this->node ){
$this->item[ $this->node->nodeName ] = $this->node->nodeValue;
}
$this->result[] = $this->item;
}
if( isset( $UnsetFields ) != NULL ):
if( strpos( $UnsetFields, ',' ) == 0 or strpos( strrev( $UnsetFields ), ',' ) == 0 ):
throw new InvalidArgumentException( 'Query Invalida, Verifique Se Há Virgulas No Inicio e No Final Da String' );
endif;
for( $i = 0; $i < count( $this->result ); $i++ ):
foreach( split( ',', str_replace( " ", NULL, $UnsetFields )) as $Index => $Field ):
unset( $this->result[$i][$Field] );
endforeach;
endfor;
endif;
return $this->result;
}
/**
* Cria Novos Elementos no Documento
* Setando Valores Para Eles
* Caso o Valor For Nulo , Cria Apenas o Elemento no Documento
* @method createElement
* @param String or Integer $Element
* @param String or Integer $Value
* @return Document
*/
public function createElement( $Element, $Value = NULL ){
$this->Element = sprintf( '%s', $Element );
$this->ElementNodeName = sprintf( '%s', strip_tags( stripslashes( $Element ) ) );
$this->Value = isset( $Value ) ? sprintf( '%s', $Value ) : '';
if( $this->Element != NULL && $this->Value != NULL ){
$this->createElement = $this->DOMDocument->createElement( $this->Element, $this->Value );
}elseif( $this->Element != NULL && $this->Value == NULL ){
$this->createElement = $this->DOMDocument->createElement( $this->Element );
}
return $this;
}
/**
* Salva o Documento Apos Suas Devidas Modificações
* Isso se o Path For Setado Corretamente Atraves
* do Metodo Load
* @method save
* @return Document
*/
public function save(){
if( isset( $this->Path ) != NULL ){
$this->DOMDocument->preserveWhiteSpace = false;
$this->DOMDocument->formatOutput = true;
$this->DOMDocument->save( sprintf( '%s', $this->Path ));
}
return $this;
}
/**
* Anexa o Elemento Criado no Documento
* Apos Ter A Invocação do Metodo ->createElement
* Espesificando seu Nome , ou Valor
* @method append
* @return Document
*/
public function append(){
$this->append = $this->DOMDocument->appendChild( $this->createElement );
return $this;
}
/**
* Cria uma Arvore De Elementos Para um Pai
* @method appendTo
* @param String or Integer $RootElement
* @param Array $Elements
* @param Array $Attributes
* @return Document
*/
public function appendTo( Array $Elements = NULL, Array $Attributes = NULL ){
$this->DOMXQuery = self::query( '../*/parent::node()[1]' );
$this->DOCRootElement = key( reset( $this->DOMXQuery ) );
foreach( $this->DOMDocument->getElementsByTagName(sprintf( '%s', $this->DOCRootElement )) as $Root ){
$this->rootElement = $this->DOMDocument->appendChild( $Root );
$this->element = $this->rootElement->appendChild( $this->createElement );
foreach( $Elements as $Key => $Value ){
$this->Elements = $this->DOMDocument->createElement( $Key, isset( $Value ) ? $Value : '' );
$this->appendedElement = $this->element->appendChild( $this->Elements );
if( count( $Attributes ) != 0 && $Attributes != NULL ){
foreach( $Attributes as $attr => $value ):
$this->appendedElement->setAttribute( $attr, $value );
endforeach;
}
}
}
return $this;
}
/**
* Altera o Valor de Um Elemento
* Você Deve Espesificar o Nome do Elemento a Ser Alterado
* é o Novo Valor Para Esse Elemento , Você Deve
* Espesificar o Path Pro Elemento na Query
* @method replace
* @param String $Query
* @param String or Integer $Element
* @param String or Integer $Value
* @return Document
*/
public function replace( $Query = NULL, $Element, $Value ){
$this->replaceElement = sprintf( '%s', $Element );
$this->replaceValue = sprintf( '%s', $Value );
if(!isset( $this->setQuery ) and $this->setQuery == NULL ){
$this->setQuery = isset( $Query ) != NULL ? sprintf( '%s/%s', $Query, $this->replaceElement ) : '';
}
if( $this->setQuery != '' || $this->setQuery != NULL ){
$this->QueryDOM = $this->DOMXPath->query( $this->setQuery );
if( $this->QueryDOM->length ){
for( $i = 0; $i < $this->QueryDOM->length; ++$i ){
$this->childs = $this->QueryDOM->item( $i );
$this->limit = $this->childClone->attributes->length;
$this->appendChanges = $this->DOMDocument->createElement( $this->replaceElement );
$this->createReplaceTextNode = $this->DOMDocument->createTextNode( $this->replaceValue );
foreach( $this->childs->attributes as $this->attr ):
$this->appendChanges->setAttribute( $this->attr->name, $this->attr->value );
endforeach;
$this->appendElement = $this->appendChanges->appendChild( $this->createReplaceTextNode );
$this->QueryDOM->item( $i )->parentNode->replaceChild( $this->appendChanges, $this->QueryDOM->item( $i ) );
}
}
}
return $this;
}
/**
* Remove Um Elemento do Documento
* Você Deve Espesificar o Path Pra Esse Elemento
* Na Query
* @method delete
* @param String $Query
* @return Document
*/
public function delete( $Query = NULL ){
if(!isset( $this->setQuery ) and $this->setQuery == NULL ){
$this->setQuery = isset( $Query ) != NULL ? sprintf( '%s', $Query ) : '';
}
if( $this->setQuery != '' || $this->setQuery != NULL ){
$this->QueryDOM = $this->DOMXPath->query( $this->setQuery );
if( $this->QueryDOM->length ){
foreach( $this->QueryDOM as $this->ResultNodes ){
$this->ResultNodes->parentNode->removeChild( $this->ResultNodes );
}
}
}
return $this;
}
/**
* Formata o Output e Trata os Espaços
* Em Branco no Documento, Setado Como Default
* False Para a Preservação de Espaços em Branco
* E True para a Formatação do Documento
* @method format
* @throws InvalidArgumentException
* @param Boolean $Whitespace
* @param Boolean $Output
* @return Document
*/
public function format( $Whitespace = False, $Output = True ){
$this->Whitespace = $Whitespace;
$this->Output = $Output;
if( !is_bool( $this->Whitespace ) ):
throw new InvalidArgumentException( sprintf( 'Entrada %s Não Suportada Para Definição De Formatação', $this->Whitespace ) );
endif;
if( !is_bool( $this->Output ) ):
throw new InvalidArgumentException( sprintf( 'Entrada %s Não Suportada Para Definição De Formatação', $this->Output ) );
endif;
if( $Whitespace != False || $Output != True ){
$this->DOMDocument->preserveWhiteSpace = $Whitespace;
$this->DOMDocument->formatOutput = $Whitespace;
}else{
$this->DOMDocument->preserveWhiteSpace = false;
$this->DOMDocument->formatOutput = true;
}
return $this;
}
/**
* Seta um Attributo Para um Elemento
* Espesificado, Os Attributos Podem Ser um Array Com Os Nomes Dos
* Attributos e Seus Respectivos Valores, Ou Apenas um Attributo
* E Seu Respectivo Valor
* @method setAttribute
* @param String $Query
* @param String or Integer $Element
* @param String or Integer $Attribute
* @param String or Integer $Value
* @return Document
*/
public function setAttribute( $Query = NULL, $Element = NULL, $Attribute , $Value = NULL){
$this->findElement = isset( $Element ) != NULL ? stripslashes( $Element ) : '';
if(!isset( $this->setQuery ) and $this->setQuery == NULL ){
if( $this->findElement != '' || $this->findElement != NULL ):
$this->setQuery = isset( $Query ) != NULL ? sprintf( '%s/%s', $Query, $this->findElement ) : '';
endif;
if( $this->findElement == '' || $this->findElement == NULL ):
$this->setQuery = isset( $Query ) != NULL ? sprintf( '%s', $Query ) : '';
endif;
}
if( is_array( $Attribute ) ):
foreach( $Attribute as $Attr => $Val ):
if( $this->setQuery != '' || $this->setQuery != NULL ):
$this->findElement = $this->DOMXPath->query( $this->setQuery );
for( $i = 0; $i < $this->findElement->length; $i ++ ):
$this->findElement->item( $i )->setAttribute(sprintf( '%s', $Attr ), sprintf( '%s', $Val ));
endfor;
endif;
endforeach;
endif;
if( $this->setQuery != '' || $this->setQuery != NULL ){
$this->findElement = $this->DOMXPath->query( $this->setQuery );
if( $this->findElement->length and !is_array( $Attribute ) ){
for( $i = 0; $i < $this->findElement->length; ++$i ){
$this->findElement->item( $i )->setAttribute(sprintf( '%s', $Attribute ), sprintf( '%s', $Value ));
}
}
}elseif( !isset( $this->setQuery ) and $this->setQuery != NULL ){
$this->element->setAttribute(sprintf( '%s', $Attribute ), sprintf( '%s', $Value ));
}
return $this;
}
/**
* Seta uma Query Para Ser Usada
* Em Toda a Interação dos Metodos
* Assim os Metodos Que Neccessitam de uma Query
* Para Localizar os Elementos no Documento Poderam
* Ser Setados Como NULL pois já Existe uma Query Como Default
* @method setDefaultQuery
* @param String $Query
* @return String
*/
public function setDefaultQuery( $Query ){
$this->setQuery = isset( $Query ) != NULL ? sprintf( '%s', $Query ) : '';
return $this->setQuery;
}
/**
* Seta um Manipulador de Banco de Dados
* Nesse Caso a Instancia de Uma Conexção Aberta
* Com o Banco de Dados, Para Poder Ser Usados Como Opçao
* De Alguns Metodos Que Converte os Registros da Sua Tabela Para XML
* Ou os Registros do XML [ Documento ] Para Registros em Sua Tabela
* @method setDBHandler
* @throws PDOException
* @param String $Server
* @param String $Username
* @param String $Password
* @param String $Database
* @return Document
*/
public function setDBHandler( $Server = NULL, $Username = NULL, $Password = NULL, $Database = NULL ){
$this->DBHandler = new PDO( "mysql:host=$Server;dbname=$Database", $Username, $Password );
if( $this->DBHandler instanceOf PDO ):
$this->DBHandler->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->DBHandler->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
$this->DBHandler->setAttribute( PDO::ATTR_TIMEOUT, 5 );
endif;
}
/**
* Transforma Registros de um Documento
* Para Registros em Sua Tabela, Você Pode Opinar Pela
* Pela Execução da Query Gerada Por Esse Metodo
* Caso Haja uma Instancia de Banco de Dados Aberta
* Caso O Ultimo Parametro $execute Não for Definido
* ou For False Apenas té retorna o SQL Gerado Pelo Metodo
* Possibilitando a Sua Execução Manualmente
* @method toSQL
* @throws OutOfBoundsException
* @throws LogicException
* @param String $table
* @param String $fields
* @param String $resultFields
* @param Boolean $execute
* @return String
*/
public function toSQL( $table, $fields, $resultFields = NULL, $execute = false ){
$this->formatedField = Array();
$this->ArrayFields = explode( ',', $resultFields );
$this->TableName = sprintf( '%s', $table );
$this->execute = $execute;
$this->TableFields = split( ',', str_replace( " ", NULL, $fields ) );
foreach( $this->TableFields as $this->TableIndex => $this->TableField ):
$this->TblField[] = '`'.$this->TableField.'`';
endforeach;
$this->data = Array();
for( $i = 0; $i < count( $this->result ); $i ++ ):
if( isset( $resultFields ) != '' || isset( $resultFields ) != NULL ){
foreach( $this->ArrayFields as $this->Field ):
if(!array_key_exists( str_replace( ' ', NULL, $this->Field ), $this->result[ $i ] ) and $resultFields != ''):
throw new OutOfBoundsException( sprintf( 'Chave %s Não Existe no Array', $this->Field ) );
endif;
$this->Field = trim( $this->Field );
$this->data[$i][$this->Field] = '\''.$this->result[$i][$this->Field].'\'';
endforeach;
}else{
foreach( $this->result[$i] as $key => $value ):
$this->data[$i][$key] = '\''.$value.'\'';
endforeach;
}
$this->formatedFields[] = "(".implode( ',', $this->data[$i] ).")";
endfor;
for( $x = 0; $x < count( $this->data ); ++$x ):
if( count( $this->TblField ) != count( $this->data[$x] ) and $resultFields != NULL ):
throw new LogicException( sprintf( 'Campos Da Tabela %s [ %s ] Não São Compatives Com %s ', $this->TableName, implode(",", $this->TblField), implode( ',', $this->data[ $x ] )));
endif;
endfor;
/*
* Inicia Montagem da Query
* O Quarto Parametro Deste Metodo
* Espesifica a Execução Da Query Apos de Pronta a Executar na Sua Tabela
* True => Monta a Query é Executa
* False => Apenas Monta a Query
*/
$this->SQLQuery = "INSERT INTO `".$this->TableName."`( ".implode( ',', $this->TblField )." ) VALUES ".implode( ',', $this->formatedFields );
if( !is_bool( $this->execute ) ):
throw new InvalidArgumentException(sprintf( 'Entrada %s Não E Valida Para uma Execução, %s Deve Ser Booleano', $this->execute, $this->execute ));
endif;
if( is_bool( $this->execute ) && $this->execute == true ):
$this->Query = $this->DBHandler->prepare( $this->SQLQuery );
$this->Query->execute();
if( !$this->Query ):
throw new LogicException( 'Não Foi Possivel Executar A Query, Verifique Sua Conexção com Banco de Dados' );
endif;
endif;
return $this->SQLQuery;
}
/**
* Transforma Registros de uma Tabela
* Para XML ou HTML, Você Deve Espesificar
* Onde Sem Encontram Esses Registros ( $table )
* E Os Campos Que Você Deseja, Assim Não é Neccessario
* Enviar Para Seu Documento Coisas Indesejaveis
* Tem Tambem Como Ultimo Parametro uma Espesificação de uma Clausa
* Você pode Fazer um Inner Join, Where, Like ou Qualquer Coisa Que Seje Possivel
* Fazer com a SQL Apos o SELECT ::campos:: FROM ::tabela:: Sua Clausula
* Escrita Manualmente, Não é Restringido o Tipo de SQL Apos a Query
* Pois Cabe ao Usuario Que Desenvolva a Aplicação Baseada no que Irá presisar
* Toda a Extração de Conteudos Que se Localizam em um Banco de Dados
* Então, Digitando uma Query Corretamente Como Especificado, Você Tera Successo
* Na Geração do Documento, Caso Contrario o Problema for no SQL, Será Disparado
* Uma Excessao Informando o Erro Cometido na Query
* @method toXML
* @throws PDOException
* @throws BadFunctionCallException
* @throws ErrorException
* @param String $table
* @param String $fields
* @param String $rootElement
* @return Document
*/
public function toXML( $table, $fields = NULL, $clause = NULL ){
$this->DBTable = $table;
$this->DBTableFields = explode( ',', str_replace( " ", NULL, $fields ));
$this->fields = Array();
$this->DBTableQuery = 'DESCRIBE `'.$this->DBTable.'`';
if( isset( $this->DBHandler ) && $this->DBHandler instanceOf PDO ){
$this->Query = $this->DBHandler->prepare( $this->DBTableQuery );
$this->Query->execute();
if( !$this->Query ){
throw new ErrorException( sprintf('Não Foi Possivel Descrever a Tabela %s', $this->DBTable) );
}else{
$this->DBTableFetch = $this->Query->fetchAll( PDO::FETCH_ASSOC );
if( $fields == '' || $fields == NULL ){
for( $i = 0; $i < count( $this->DBTableFetch ); ++$i ){
$this->fields[] = $this->DBTableFetch[$i]['Field'];
}
}elseif( isset( $this->DBTableFields ) != NULL ){
$this->fields = $this->DBTableFields;
}
$this->SQLClause = isset( $clause ) != NULL ? sprintf( '%s', $clause ) : '';
$this->DOMXQuery = self::query( '../*/parent::node()[1]' );
$this->DOCRootElement = key( reset( $this->DOMXQuery ) );
$this->TblFields = count( $this->fields ) != 0 ? implode( ',', $this->fields ) : '*';
$this->DBTableDataSelect = $this->DBHandler->prepare( 'SELECT '. $this->TblFields .' FROM `'.$this->DBTable.'` '.$this->SQLClause.'' );
$this->DBTableDataSelect->execute();
$this->DBTableData = $this->DBTableDataSelect->fetchAll( PDO::FETCH_ASSOC );
foreach( $this->DBTableData as $DataValue ){
foreach( $this->DOMDocument->getElementsByTagName(sprintf( '%s', $this->DOCRootElement )) as $this->RootElement ){
$this->Root = $this->DOMDocument->appendChild( $this->RootElement );
$this->ElementName = $this->Root->appendChild( $this->DOMDocument->createElement( $this->DBTable ) );
foreach( $DataValue as $this->Index => $this->Data ){
$this->ElementName->appendChild( $this->DOMDocument->createElement( utf8_encode( $this->Index ), utf8_encode( $this->Data ) ) );
}
}
}
}
}elseif( !isset( $this->DBHandler ) ){
throw new BadFunctionCallException( 'Não Foi Possivel Encontrar a Instancia do Banco De Dados' );
}elseif( isset( $this->DBHandler ) && !$this->DBHandler instanceOf PDO ){
throw new BadFunctionCallException( 'A Instancia do Banco de Dados Não é Uma Instancia Suportada' );
}
return $this;
}
/**
* Codifica Dados Retornados no Resultado da Query
* Para o Formato JSON, Java Script Object Notation
* @method toJSON
* @param String $Query
* @return String, JSON Encoded
*/
public function toJSON( $Query = NULL ){
if(!isset( $this->setQuery ) and $this->setQuery == NULL ){
$this->setQuery = isset( $Query ) != NULL ? sprintf( '%s', $Query ) : '';
}
$this->results = self::query( $this->setQuery );
$this->json = json_encode( $this->result );
return $this->json;
}
/**
* Converte Do Formato JSON Para XML
* O Metodo Para Criar o Elemento Pai Para os Childs
* Deve Ser Criado Atraves de ->createElement, no Qual Retorna uma Instancia
* de DOMNode para Criação dos Filhos Atraves Dele
* @method fromJSON
* @param String $JSON
* @return Document
*/
public function fromJSON( $JSON ){
$this->JSONString = $JSON;
if( $this->JSONString == NULL || $this->JSONString == '' ){
throw new LogicException( 'String do JSON Está Vazia' );
}else{
$this->JSON = json_decode( $this->JSONString, true );
$this->DOMXQuery = self::query( '../*/parent::node()[1]' );
$this->DOCRootElement = key( reset( $this->DOMXQuery ) );
for( $j = 0; $j < count( $this->JSON ); $j++ ):
foreach( $this->DOMDocument->getElementsByTagName(sprintf( '%s', $this->DOCRootElement ) ) as $this->RootElement ):
$this->Root = $this->DOMDocument->appendChild( $this->RootElement );
$this->ElementName = $this->Root->appendChild( $this->DOMDocument->createElement( $this->ElementNodeName ) );
foreach( $this->JSON[$j] as $this->Index => $this->Data ):
$this->ElementName->appendChild( $this->DOMDocument->createElement( utf8_encode( $this->Index ), utf8_encode( $this->Data ) ) );
endforeach;
endforeach;
endfor;
}
return $this;
}
}
Arquivos Para Download:
:seta: http://www.mediafire.com/?fbzfqs751schc4r