2014-10-01 50 views
1

我有XML文件,我嘗試獲得價值。我需要從變量media_id值12345。我怎樣才能得到它與PHP和simplexml?如何使用simplexml獲得價值?

<?xml version="1.0" encoding="UTF-8"?> 
<Playerdata> 
    <Clip> 
     <MediaType>video_episode</MediaType> 
     <Duration>5400</Duration> 
     <PassthroughVariables> 
      <variable name="media_type" value="video_episode"/> 
      <variable name="media_id" value="12345"/> 
     </PassthroughVariables> 
    </Clip> 
</Playerdata> 

我現在只有:

$xml = simplexml_load_file("file.xml"); 

回答

0

試試這個:

$xml = simplexml_load_file("file.xml"); 
$variable = $xml->xpath('//variable[@name="media_id"]')[0]; 
echo $variable["value"]; 
0

您可以加載XML文件到了SimpleXML將分析它,並返回一個SimpleXML的對象。

$xml = simplexml_load_file('path/to/file.xml'); 
//then you should be able to access the data through objects 
$passthrough = $xml->Clip->PassthroughVariables; 
//because you have many children in the PassthroughVariables you'll need to iterate 
foreach($passthrough as $p){ 
    //to get the attributes of each node you'll have to call attributes() on the object 
    $attributes = $p->attributes(); 
    //now we can iterate over each attribute 
    foreach($attributes as $a){ 
     //SimpleXML will assume each data type is a SimpleXMLElement/Node 
     //so we need to cast it for comparisons 
     if((String)$a->name == "media_id"){ 
      return (int)$a->value; 
     } 
    } 
} 

SimpleXMLElement文檔可能是處理SimpleXMLObject的一個很好的起點。 http://uk1.php.net/manual/en/class.simplexmlelement.php

0

這裏是W/O的Xpath

$xml = simplexml_load_file('file.xml'); 
$value = (int) $xml->Clip->PassthroughVariables->variable[1]['value'];