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

How to Extract Attribute Values from XML in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 13:43:02701browse

How to Extract Attribute Values from XML in PHP?

Accessing Attribute Values from XML in PHP

Retrieving attribute values from an XML file in PHP can be straightforward using the simplexml_load_file() function and the attributes() method.

Question:

How can I obtain the value of the VarNum attribute from the following XML fragment:

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

Answer:

To access the VarNum attribute, we can use the attributes() method as follows:

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

This code iterates through all attributes of the first element and prints the attribute name and value pairs. To retrieve the VarNum attribute specifically, we can use:

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

The above is the detailed content of How to Extract 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