Ler Atributos XML – Extendendo a Classe SimpleXMLElement

Publicado: janeiro 27, 2012 em PHP, XML
Tags:, , , , , ,

Ler Atributos XML – Extendendo a Classe SimpleXMLElement

Opa!

Vamos criar uma Classe Extendida para ler os atributos de um XML,  iremos extender  a SimpleXMLElement.
Para carregar o XML vamos utilizar o SimpleXml, não se assuste com tantos nomes de classes, o que precisamos fazer para ler os atributos é bem simples! 

O XML é o padrão de sempre, uma playlist…  =D

<?xml version="1.0" encoding="iso-8859-1"?>
<playlist>
 <faixa>
 <titulo id="55" duracao="04:08" mp3="http://site.com/mp3/atari/01.mp3">Revolution Action</titulo>
 <album>60 Second Wipe Out</album>
 <autor>Atari Teenage Riot</autor>
 </faixa>
 <faixa>
 <titulo id="50" duracao="03:55" mp3="http://site.com/mp3/atari/03.mp3">Speed</titulo>
 <album>60 Second Wipe Out</album>
 <autor>Atari Teenage Riot</autor>
 </faixa>
</playlist>

Extendendo a Classe SimpleXMLElement e lendo o XML

<?php
//extendendo a classe SimpleXMLElement
//neste caso a classe SimpleXMLAttribute extende a classe SimpleXMLElement
//com o novo método Attribute
class SimpleXMLAttribute extends SimpleXMLElement
{
// metodo retorna o valor do atributo
 public function Attribute( $name )
 {
 // percorre os atributos
 foreach( $this->Attributes() as $key => $val )
 {
 // verifica existencia e retorna o valor
 if( $key == $name )
 {
 //converte/retorna valor string
 return (string) $val;
 }
 }
 }
}

//carregando o XML com o simplexml passamos como parametro a classe SimpleXMLAttribute
//esse parametro deve ser uma classe que extenda o SimpleXMLElement
$xml = simplexml_load_file( "playlist.xml", 'SimpleXMLAttribute' );
//percorrendo o nó faixa da playlist
foreach( $xml->faixa as $faixa )
{
 //printando valores e atributos
 echo
 $faixa->titulo
 . "<br />"
 //retorna o atributo id passado ao método Attribute()
 . $faixa->titulo->Attribute( 'id' )
 . "<br />"
 //retorna o atributo duracao
 . $faixa->titulo->Attribute( 'duracao' )
 . "<br />"
 //ja deu para entender né
 . $faixa->titulo->Attribute( 'mp3' )
 . "<br />"
 //retorna o album
 . $faixa->album
 . "<br />"
 //retorna o autor
 . $faixa->autor
 . "<br /> <br />";
}
//descomente a linha abaixo p/ ver os atributos
//echo "<pre>"; print_r($xml->faixa); print_r($xml->faixa->titulo);
?>

Output’s:

Download dos fontes

Referências:
Extends
SimpleXMLElement
SimpleXML
Enjoy!!!

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Sair / Alterar )

Imagem do Twitter

You are commenting using your Twitter account. Sair / Alterar )

Foto do Facebook

You are commenting using your Facebook account. Sair / Alterar )

Connecting to %s