maexus Posted March 23, 2008 Share Posted March 23, 2008 I don't know if this is just isolated to when you use simplexml but here is basicly the jist of whats happening. Consider the following XML <parent> <child> <name>John</name> <gender>m</gender> </child> <child> <name>Sarah</name> <gender>f</gender> </child> </parent> I'm trying to assign the string value of the child->name to an array key. Like this: $array[$simplexml->child[0]->name][] = "data"; The only problem is, PHP doesn't let you assign objects or arrays as array keys. So I assign it. $temp = $simplexml->child[0]->name; $array[$temp][] = "data"; Same issue though. However, if I run it though a function first, it works fine. $temp = trim($simplexml->child[0]->name); $array[$temp][] = "data"; This is.. sloppy to have in my code though. Is there a way to extract the string value from the simplexml object? Link to comment https://forums.phpfreaks.com/topic/97509-getting-the-string-value-from-an-objects-property/ Share on other sites More sharing options...
uniflare Posted March 23, 2008 Share Posted March 23, 2008 have you tried: $array["$simplexml->child->name"][] = "data"; ? Link to comment https://forums.phpfreaks.com/topic/97509-getting-the-string-value-from-an-objects-property/#findComment-498922 Share on other sites More sharing options...
Barand Posted March 23, 2008 Share Posted March 23, 2008 try <?php $str = '<parent> <child> <name>John</name> <gender>m</gender> </child> <child> <name>Sarah</name> <gender>f</gender> </child> </parent>'; $xml = simplexml_load_string($str); $array = array(); foreach ($xml->child as $ch) { $array[(string)$ch->name] = (string)$ch->gender; } echo '<pre>', print_r($array, true), '</pre>'; ?> --> Array ( [John] => m [sarah] => f ) Link to comment https://forums.phpfreaks.com/topic/97509-getting-the-string-value-from-an-objects-property/#findComment-498925 Share on other sites More sharing options...
maexus Posted March 23, 2008 Author Share Posted March 23, 2008 Thanks Link to comment https://forums.phpfreaks.com/topic/97509-getting-the-string-value-from-an-objects-property/#findComment-498929 Share on other sites More sharing options...
Barand Posted March 23, 2008 Share Posted March 23, 2008 For information Another way to cast a variable as a string is to put it inside double quotes, so you could also do this $array = array(); foreach ($xml->child as $ch) { $array["$ch->name"] = "$ch->gender"; } Link to comment https://forums.phpfreaks.com/topic/97509-getting-the-string-value-from-an-objects-property/#findComment-498930 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.