1

I have XML-file and i try to get value. I need value 12345 from variable media_id. How i can get it with php and 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>

I have now only:

$xml = simplexml_load_file("file.xml");
Rane
  • 51
  • 5

3 Answers3

0

You can load your XML file into Simplexml which will parse it and return an SimpleXML object.

$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;
        }
    }
}

The SimpleXMLElement documentation is probably a good starting point when it comes to working with the SimpleXMLObject. http://uk1.php.net/manual/en/class.simplexmlelement.php

inkysplat
  • 1
  • 1
0

Try this:

$xml = simplexml_load_file("file.xml");
$variable = $xml->xpath('//variable[@name="media_id"]')[0];
echo $variable["value"];
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

Here is w/o Xpath

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