user2571510
user2571510

Reputation: 11377

How to convert simpleXML string to array

I am fetching keywords from an SQL table which returns a simpleXML string that looks like the following:

<ranks>
  <tags>
    <tag>Alabama</tag>
    <tagID>1</tagID>
  </tags>
  <tags>
    <tag>Alaska</tag>
    <tagID>2</tagID>
  </tags>
  <tags>
    <tag>Arizona</tag>
    <tagID>3</tagID>
  </tags>
</ranks>

Now I would need this in the form of an array that I can store as a variable.

Can someone tell me how to achieve this ? I am pretty new to arrays and did not know a way to start here as there are always two values for each tag, i.e. the tag name and the tagID whereas I only need an array with the tag names. Ideally the result should look something like the following:

$tags = ['Alabama', 'Alaska', 'Arizona'];

Upvotes: 0

Views: 82

Answers (1)

NadirDev
NadirDev

Reputation: 71

Use this function:

function xml_to_array($xml,$main_heading = '') {
    $deXml = simplexml_load_string($xml);
    $deJson = json_encode($deXml);
    $xml_array = json_decode($deJson,TRUE);
    if (! empty($main_heading)) {
        $returned = $xml_array[$main_heading];
        return $returned;
    } else {
        return $xml_array;
    }
}

You can make an array of your XML by the following code:

    $simple = 'your xml';
    $data_array = xml_to_array($simple);

If your XML is a single file, get the file content with file_get_contents();

Upvotes: 1

Related Questions