2013-05-17 4 views
0

J'essaie d'obtenir des données du fichier XML. Les données se présente comme suit:Obtention de données à partir du fichier XML

<MeasuringPoints> 
<MeasuringPoint ID="Base" LastChange="2013-05-17T09:29:59.293" WeatherCondition="8"> 
    <Name LngID="IT">Name 1</Name> 
    <Name LngID="DE">Name 2</Name> 
    <Name LngID="EN>Name 3</Name> 
</MeasuringPoint> 
<MeasuringPoint ID="Middle" LastChange="2012-08-01T11:47:33.160" WeatherCondition="14"> 
    <Name LngID="IT">Name 1a</Name> 
    <Name LngID="DE">Name 2a</Name> 
    <Name LngID="EN">Name 3a</Name> 
</MeasuringPoint> 
<MeasuringPoint ID="Top" LastChange="2013-05-17T09:29:59.293" WeatherCondition="8"> 
    <Name LngID="DE">Name 1b</Name> 
    <Name LngID="IT">Name 2b</Name> 
    <Name LngID="EN">Name 3b</Name> 
</MeasuringPoint> 
</MeasuringPoints> 

J'ai aussi ce code php:

foreach ($xml->Area as $area) 
{  
    $MEASURING_POINTS = $area->MeasuringPoints->MeasuringPoint['ID']; 
    $MEASURING_LAST_CHANGE = $area->MeasuringPoints->MeasuringPoint['LastChange']; 

    echo $MEASURING_POINTS; 
    echo " - "; 
    echo $MEASURING_LAST_CHANGE; 
} 

Le code fonctionne mais seulement pour la première MeasuringPoint (l'ID Base). Comment obtenir les données d'autres MeasuringPoint (Middle et Top ID)?

Merci pour toute aide!

Adrian

+0

Pourquoi itérez n'êtes-vous pas par 'MeasuringPoints' à la place? –

Répondre

0

Vous devez iteratore sur MeasuringPoint.

Essayez ceci:

foreach ($xml->Area as $area) 
{  
    foreach($area->MeasuringPoints->MeasuringPoint as $point) { 
     $MEASURING_POINT = $point['ID']; 
     $MEASURING_LAST_CHANGE = $point['LastChange']; 

     echo $MEASURING_POINT; 
     echo " - "; 
     echo $MEASURING_LAST_CHANGE; 
    } 
} 

Pour seulement obtenir le troisième MeasuringPoint essayez ceci:

foreach ($xml->Area as $area) 
{  
    $point = $area->xpath("/MeasuringPoints/MeasuringPoint[@ID='Top']") 
    $MEASURING_POINT = $point['ID']; 
    $MEASURING_LAST_CHANGE = $point['LastChange']; 

    echo $MEASURING_POINT; 
    echo " - "; 
    echo $MEASURING_LAST_CHANGE; 
} 
+0

Vous avez raison! Maintenant fonctionne parfaitement! – Adrian

+0

J'ai une autre question - Est-il possible d'obtenir des données uniquement à partir de 'MeasuringPoint ID =" Top "' section? – Adrian

+0

Bien sûr, mais dans ce cas, vous devez utiliser X-Path. Voir http://php.net/manual/en/simplexmlelement.xpath.php pour la méthode et http://www.w3schools.com/xpath/ pour une courte introduction. J'ai mis à jour la réponse pour votre cas spécifique. –

Questions connexes