Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Querying array name

Having a really dumb moment..

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>

How can I simply fetch the value of type name="XX" ?
So in the case of the above data snippet it would fetch ACOGOptic

>Solution :

You can simply iterate over the type elements and check the value of the name attribute:

$xml = <<<XML
<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>
    <type name="Other">
        <nominal>20</nominal>
        <quantmin>0</quantmin>
        <quantmax>30</quantmax>
    </type>
</types>
XML;

$sx = simplexml_load_string($xml);
foreach($sx->type as $type)
{
    if($type['name'] == 'ACOGOptic')
        printf('Nominal: %s  Min: %s  Max: %s  Category: %s', $type->nominal, $type->quantmin, $type->quantmax, $type->category['name');
}

Output:

Nominal: 15  Min: -1  Max: 1  category: weapons
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading