Jump to content

getting the string value from an object's property?


maexus

Recommended Posts

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?

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
)

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";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.