Home >Backend Development >PHP Tutorial >How to Retrieve Attribute Values from XML in PHP?

How to Retrieve Attribute Values from XML in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 02:17:02405browse

How to Retrieve Attribute Values from XML in PHP?

Getting Attribute Values from XML in PHP

Retrieving attribute values from an XML file can be a straightforward task in PHP using the SimpleXMLElement class.

Suppose you have an XML file that resembles this:

<VAR VarNum="90">
  <option>1</option>
</VAR>

To obtain the value of the VarNum attribute, you can leverage the attributes() method of the SimpleXMLElement object.

$xml = simplexml_load_file($file);
foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) {
    echo "$attributeName=\"$attributeValue\"\n";
}

This code iterates through all the attributes of the first Var element and prints their names and values in a structured format.

Alternatively, you can directly access the attribute value by name:

$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];

The above is the detailed content of How to Retrieve Attribute Values from XML in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn