0

I'm trying to read an XML file into an array and I'm having a little bit of trouble. Here is what my code looks like so far:

 $inst = new SimpleXMLElement($xml);
 foreach( $inst->xpath("record[@id='" . $range . "']") as $u ) {
      foreach($fields as $field) {
          $results[$field] = $u->$field;
      }
 }

But when I do print_r($results), this is what's outputted:

Array
(
[field1] => SimpleXMLElement Object
    (
        [0] => field1Data
    )

[field2] => SimpleXMLElement Object
    (
        [0] => field2Data
    )

[field3] => SimpleXMLElement Object
    (
        [0] => field3Data
    )
)

How can I get the data straight from the SimpleXMLElement Object and store it in the array rather than having it do this? I tried accessing it as an array like $u->$field[0] but that didn't work either.

hakre
  • 193,403
  • 52
  • 435
  • 836
SISYN
  • 2,209
  • 5
  • 24
  • 45

1 Answers1

0

Casting a SimpleXMLElement to string is the general solution(see "Forcing a SimpleXML Object to a string, regardless of context" for the canonical question), for a complete array containing all SimpleXMLElements like returned by xpath() or like you create it your own, a common way is to map the array onto trim:

$results = array_map('trim', $results);

or strval:

$results = array_map('strval', $results);

For example:

$inst    = new SimpleXMLElement($xml);
list($u) = $inst->xpath("record[@id='" . $range . "']")
foreach ($fields as $field) {
    $results[$field] = $u->$field;
}

$results = array_map('strval', $results);
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836