Friday, 31 August 2018

Problem of building an associative array from xml

I'm trying to build an associative array from XML. Here is what xml looks like (total of about 70 'item' entries):

<xmldata>
<source>source</source>
<release>release</release>
 <item>
  <name>Name</name>
  <date>1/1/2015</date>
  <time>10AM</time>
  <value>24</value>
 </item>
 <item>
  <name>Name</name>
  <date>1/1/2015</date>
  <time>10AM</time>
  <value>24</value>
 </item>
etc
...
</xmldata>

Here is what I've tried so far:
$data = file_get_contents("xml url");
$xml = simplexml_load_string($data);
$counter = 1;
$new_array = array();
foreach($xml->children() as $item)
{
  if($counter > 2)
  {
    $temp_array = array('name' => $item->name, 'value' => $item->value);
    array_push($newArray, $temp_array);
  }
}

I'm trying to build an associative array that looks like this:
$new_array = array(array("name"=>name, "value"=>value),array("name"=>name,  "value"=>value),array("name"=>name, "value"=>value), etc);

It's not working. I try to print the array to see if it is formed but I get a list of 0-array, 1-array, etc.
I've also tried array_merge(), and $new_array[] = $item, and array_push($new_array, array("name"=>name, "value"=>value));
Is there a preferred way to append associative arrays onto an array? i.e. like array.append(dict) in python? Thanks much!

try like that
$data = file_get_contents("xml url");
$xml = simplexml_load_string($data);
$counter = 1;
$new_array =[];
foreach($xml->children() as $item)
{
    $new_array[$counter]['name'] = $item->name;
    $new_array[$counter]['value'] = $item->value;
    $counter += 1;
}

0 comments:

Post a Comment