0

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'];

1 Answer 1

1

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();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.