2012-05-10 29 views
18

El XML que estoy leyendo el siguiente aspecto:PHP SimpleXML + Obtener Atributo

<show id="8511"> 

    <name>The Big Bang Theory</name> 
    <link>http://www.tvrage.com/The_Big_Bang_Theory</link> 
    <started>2007-09-24</started> 
    <country>USA</country> 

    <latestepisode> 
     <number>05x23</number> 
     <title>The Launch Acceleration</title> 
    </latestepisode> 

</show> 

Para obtener (por ejemplo) el número del último episodio, lo haría:

$ep = $xml->latestepisode[0]->number; 

Estos trabajos esta bien Pero, ¿qué haría para obtener la identificación del <show id="8511">?

He intentado algo así como:

$id = $xml->show; 
$id = $xml->show[0]; 

Pero nada funcionó.

actualización

Mi fragmento de código:

$url = "http://services.tvrage.com/feeds/episodeinfo.php?show=".$showName; 
$result = file_get_contents($url); 
$xml = new SimpleXMLElement($result); 

//still doesnt work 
$id = $xml->show->attributes()->id; 

$ep = $xml->latestepisode[0]->number; 

echo ($id); 

Ori. XML:

http://services.tvrage.com/feeds/episodeinfo.php?show=The.Big.Bang.Theory 
+0

http://php.net/ simplexml.examples-basic – hakre

+0

posible duplicado de [Acceso @attribute desde SimpleXML] (http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml) - para la referencia. – hakre

+0

ver: http://stackoverflow.com/questions/10537657/php-simplexml-get-attribute/19289857#19289857 –

Respuesta

31

Esto debería funcionar.

$id = $xml["id"]; 

Su raíz XML se convierte en la raíz del objeto SimpleXML; su código está llamando a una raíz chid con el nombre de 'show', que no existe.

También puede utilizar este enlace para algunos tutoriales: http://php.net/manual/en/simplexml.examples-basic.php

+2

¡Esto parece hacer el truco! ¡Muchas gracias! (Probablemente debería tomar más tiempo para mirar los ejemplos la próxima vez :() – Andrej

12

Es necesario utilizar attributes

creo que esto debería funcionar

$id = $xml->show->attributes()->id; 
+0

Esto no funcionaría ... el 'show' es la raíz predeterminada ... él necesita warp el 'xml' correctamente – Baba

+0

Desafortunadamente sigo recibiendo' Advertencia: main() [function.main]: El nodo ya no existe en .... ' – Andrej

7

Es necesario utilizar attributes() para obtener los atributos.

$id = $xml->show->attributes()->id; 

También puede hacer esto:

$attr = $xml->show->attributes(); 
$id = $attr['id']; 

O puede probar esto:

$id = $xml->show['id']; 

En cuanto a la edición en su pregunta (<show> es su elemento raíz), intenta esto :

$id = $xml->attributes()->id; 

O

$attr = $xml->attributes(); 
$id = $attr['id']; 

O

$id = $xml['id']; 
+0

Desafortunadamente, el primer y el segundo ejemplo muestran' Warning: main() [function.main ]: El nodo ya no existe en .... ', mientras que el último no muestra nada. – Andrej

+0

@Andrej: verifica mi edición. –

+0

Funciona, házmelo saber en caso de que hayas editado la respuesta de @ Sam también, porque cambiaría la respuesta correcta y eliges la tuya ahora. – Andrej

0

es necesario formatear su XML correctamente y hacer que tenga examply usando <root></root> o <document></document> nada ..véase la especificación XML y ejemplos en http://php.net/manual/en/function.simplexml-load-string.php

$xml = '<?xml version="1.0" ?> 
<root> 
<show id="8511"> 
    <name>The Big Bang Theory</name> 
    <link>http://www.tvrage.com/The_Big_Bang_Theory</link> 
    <started>2007-09-24</started> 
    <country>USA</country> 

    <latestepisode> 
     <number>05x23</number> 
     <title>The Launch Acceleration</title> 
    </latestepisode> 

</show> 
</root>'; 

$xml = simplexml_load_string ($xml); 
var_dump ($xml->show->attributes()->id); 
+0

Desafortunadamente, no tengo ninguna influencia sobre cómo se formatea el xml! – Andrej

+0

¡Agregué la fuente XML original a mi publicación! – Andrej

0

Después de haber cargar correctamente el archivo XML utilizando el SimpleXML objecto que puede hacer un print_r($xml_variable) y se puede encontrar fácilmente los atributos que puede tener acceso. Como otros usuarios dijeron $xml['id'] también funcionó para mí.

8

Esto debería funcionar. Es necesario utilizar atributos con el tipo (si el valor picadura de uso (cadena))

$id = (string) $xml->show->attributes()->id; 
var_dump($id); 

O esto:

$id = strip_tags($xml->show->attributes()->id); 
var_dump($id); 
3

prueba este

$id = (int)$xml->show->attributes()->id; 
Cuestiones relacionadas