如何用simplexml获得价值?

时间:2014-10-01 10:45:01

标签: php xml simplexml

我有XML文件,我试图获得价值。我需要来自变量media_id的值12345。我怎么能用php和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");

3 个答案:

答案 0 :(得分:0)

您可以将XML文件加载到Simplexml中,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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

这是没有Xpath

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