简体   繁体   中英

Extract Last Data Tag from Last XML element using PHP

I have an XML file which I have used xpath to extract the last Element.

So at the moment this line of code below:

    //Get The file from directory
    $xml=simplexml_load_file("docs/03-24-2014.xml");

    //Get last Element
    $last = $xml->xpath("/DocumentElement/Datas[last()]");

Output

array(1) { [0]=> object(SimpleXMLElement)#4 (6) { ["Name"]=> string(12) "COM3-Screen1" ["AdjustMode"]=> string(10) "AutoAdjust" ["Time"]=> string(19) "03-24-2014 11:59:27" ["ScreenBrightnessValues_x0028_0-255_x0029_"]=> string(1) "2" ["AmbientBrightness_x0028_lux_x0029_"]=> string(1) "0" ["BrightnessPercentage"]=> string(2) "0%" } }

Goal

What am trying to achieve is extract the last data tag called "BrightnessPercentage and store it in a string"

I tried echo $last->BrightnessPercentage .; but it didnt work!

Any help you be kindly appreciated

To get that attribute directly from xpath as string, do:

$brightness = (string)$xml->xpath("/DocumentElement/Datas[last()]/@BrightnessPercentage")[0];

requires PHP >= 5.4. If you are on a lower version, do:

$brightness = $xml->xpath("/DocumentElement/Datas[last()]/@BrightnessPercentage");
$brightness = (string)$brightness[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM