-2

So I have an array of objects called $locations, each object is a SimpleXMLElement, each object in this array:

foreach ($locations as $key => $location) {
    var_dump($location);
}

die();   

Looks like:

object(SimpleXMLElement)#2 (9) {
  ["@attributes"]=>
  array(2) {
    ["fb"]=>
    string(0) ""
    ["ll"]=>
    string(21) "44.1097932,-79.584537"
  }
  ["label"]=>
  string(8) "Bradford"
  ["name"]=>
  string(8) "Bradford"
  ["address"]=>
  string(52) "448 Holland Street West, Unit 3 Bradford, ON L3Z 2A4"
  ["phone"]=>
  string(14) "(905) 551-9463"
  ["fax"]=>
  object(SimpleXMLElement)#24 (0) {
  }
  ["mngr"]=>
  string(12) "OPENING SOON"
  ["email"]=>
  object(SimpleXMLElement)#25 (0) {
  }
  ["hours"]=>
  object(SimpleXMLElement)#26 (0) {
  }
}

Now I want the string, not the objet, but the string name from each of these objects in an associative array with a key of $key and a $value of of name. So I did:

$organizedLocations = array ();
foreach ($locations as $key => $location) {
    var_dump($location, $location->name);
    $organizedLocations[$key] = $location->name;
}

die();

Notice the var_dump. $location->name is:

object(SimpleXMLElement)#23 (1) {
  [0]=>
  string(8) "Bradford"
}

This is not what I want. I want, in this case: "Bradford", not some object with a string. I tried doing $location->name->0 I even tried looping over $location->name in a foreach and I tried $location->name[0] none of those worked.

How do I get Bradford out of the object and into my array as a value to the $key?

TheWebs
  • 12,470
  • 30
  • 107
  • 211
  • Why was this down voted? I showed clear examples, the problem is well out lined. What am I missing? Where is the feedback, to make the question better? – TheWebs Jan 15 '15 at 22:06
  • 1
    This link should help you: [Converting a SimpleXML Object to an Array][1] [1]: http://stackoverflow.com/questions/6167279/converting-a-simplexml-object-to-an-array – Yolo Jan 15 '15 at 22:10
  • @Yolo, this is probably the best solution IF you can afford the overhead of encoding and decoding the XML to JSON. I found it to be a bit slow and high on RAM consumption on large (3k+ objects) XML objects. But yeah, generally that's what I'd do:) – Ignas Jan 15 '15 at 22:13

2 Answers2

1

The correct way to do this is to cast it to a string as then I will get my actual value I want to then store in an array:

 (string) $location->name;
TheWebs
  • 12,470
  • 30
  • 107
  • 211
0

Possible duplicate. Maybe these threads are what you need

Forcing a SimpleXML Object to a string, regardless of context

Get value from SimpleXMLElement Object

Community
  • 1
  • 1
mattmc
  • 479
  • 5
  • 14