I am trying to fetch data from an XML file and have converted it to JSON.
$xml = simplexml_load_file('types.xml','SimpleXMLElement',LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
The XML file contains data structured as:
<types>
<type name="ACOGOptic">
<nominal>15</nominal>
<lifetime>14400</lifetime>
<restock>1800</restock>
<min>8</min>
<quantmin>-1</quantmin>
<quantmax>-1</quantmax>
<cost>100</cost>
<flags count_in_cargo="0" count_in_hoarder="0" count_in_map="1" count_in_player="0" crafted="0" deloot="0"/>
<category name="weapons"/>
<usage name="Military"/>
</type>
</types>
How can I simply fetch the value of type name="XX"?
In the above case, the desired result would be ACOGOptic
.
2
Answers
You can simply iterate over the
type
elements and check the value of thename
attribute:Output:
As demonstrated at Using XPath to extract XML in PHP, (although not required in the asked question) xpath is a very direct tool to extract the unknown tag name without looped checks.
Code: (Demo)