Home > Software design >  Getting exact data from xml to array [PHP]
Getting exact data from xml to array [PHP]

Time:06-30

i m trying to get some data from the xml out of prestashop api To be exact, i want to create an array which will have as key the id (ex. 2) and value the name->language. I am using simplexml_load_string to convert the xml to arrays

    <?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <category>
        <id>
            <![CDATA[2]]>
        </id>
        ...
        <name>
            <language id="1" xlink:href="https://mosty.com/api/languages/1">
                <![CDATA[Home]]>
            </language>
        </name>
        <link_rewrite>
            <language id="1" xlink:href="https://mosty.com/api/languages/1">
                <![CDATA[home]]>
            </language>
        </link_rewrite>
        ...
    </category>
</prestashop>

CodePudding user response:

Please have a look at the code below. I suppose you have multiple <category> elements:

Code

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <category>
        <id>
            <![CDATA[2]]>
        </id>
        <name>
            <language id="1" xlink:href="https://mosty.com/api/languages/1">
                <![CDATA[Home]]>
            </language>
        </name>
        <link_rewrite>
            <language id="1" xlink:href="https://mosty.com/api/languages/1">
                <![CDATA[home]]>
            </language>
        </link_rewrite>
    </category>
</prestashop>';

$obj = simplexml_load_string($xml);

$result = [];
foreach($obj->category as $item) {
    $result[trim($item->id)] = trim($item->name->language);
}
var_dump($result);

Output

array(1) { [2]=> string(4) "Home" }
  • Related