使用php从XML文件中读取属性值

With this XML file with structure:

<?xml version="1.0"?>
<element>
    <child attrName="something"/>
</element>

i can access with php to read attrName value with expression:

<?php
$xml = simplexml_load_file("fileAbove.xml") or die("Error: Cannot create object");
foreach($xml->children() as $child) {
    if($child->getName() == "element") {
        $attrValue = $xml->xpath('/element/child/@attrName');
        echo $attrValue;
    }
}
?>

So result will be:

something

But how with this file structure i can't get attrValue with same php code from above?

<?xml version="1.0"?>
<element someAttr="" otherAttr="">
    <child attrName="attrValue"/>
</element>

I'm geting error:

Notice: Undefined offset: 0

Does anybody know what i miss?

Thank you

Even with your first example it was returning null. The below code should solve your issues.

fileAbove.xml:

<?xml version="1.0"?>
<element someAttr="" otherAttr="">
 <child attrName="attrValue"/>
</element>

readchild.php

<?php
  $xml = simplexml_load_file("fileAbove.xml") or die("Error: Cannot create object");
  foreach($xml->child[0]->attributes() as $a) {
    echo $a . "
";
  }
?>

Result is below:

[root@web01 temp]# php readchild.php
attrValue
[root@web01 temp]#