Brando2600 Brando2600 - 6 months ago 11
PHP Question

Why can't I seem to access elements of a multi dimensional array?

I have an XML file that was converted into an array with xpath. Ultimately I want to be able to access the variables in the array but no method seems to work.

echo $items['member']['name'];
Does not work

echo $items['name'];
Nor this

echo $items['members']['member']['name'];
Nor this

echo $items[0][0]
Nor this

echo $items[0]
Nor this

echo $items[0]['object']['name']
Nor this

$items[0]['name']
Nor this

I have no no what the problem is but I imagine it might be with xpath and it's effect on the array. I understand that there are other similar threads but no resource seems to help.

PHP:


$xml = simplexml_load_file('XML/profiles.xml'); //Create XML variable from XML file.

$items = $xml->xpath('member');

var_dump($items);
?>


XML:


<member>
<name>AndrewHarvey</name>
<location>Carleton-Victoria</location>
<party>L</party>
</member>

<member>
<name>BenoitBourque</name>
<location>Kent North</location>
<party>L</party>
</member>

<member>
<name>BernardLeBlanc</name>
<location>Memramcook-Tantramar</location>
<party>L</party>
</member>

<member>
<name>BertrandLeBlanc</name>
<location>Kent North</location>
<party>L</party>
</member>

<member>
<name>BillFraser</name>
<location>Miramichi</location>
<pos>Tourism</pos>
<pos>Heritage and Culture</pos>
<pos>Northern and Miramichi Funds</pos>
<party>L</party>
</member>
and so on...


Var dump of $array:

array (size=49)
0 =>
object(SimpleXMLElement)[2]
public 'name' => string 'AndrewHarvey' (length=12)
public 'location' => string 'Carleton-Victoria' (length=17)
public 'party' => string 'L' (length=1)
1 =>
object(SimpleXMLElement)[3]
public 'name' => string 'BenoitBourque' (length=13)
public 'location' => string 'Kent North' (length=10)
public 'party' => string 'L' (length=1)
2 =>
object(SimpleXMLElement)[4]
public 'name' => string 'BernardLeBlanc' (length=14)
public 'location' => string 'Memramcook-Tantramar' (length=20)
public 'party' => string 'L' (length=1)
3 =>
object(SimpleXMLElement)[5]
public 'name' => string 'BertrandLeBlanc' (length=15)
public 'location' => string 'Kent North' (length=10)
public 'party' => string 'L' (length=1)
4 =>
object(SimpleXMLElement)[6]
public 'name' => string 'BillFraser' (length=10)
public 'location' => string 'Miramichi' (length=9)
public 'pos' =>
array (size=3)
0 => string 'Tourism' (length=7)
1 => string 'Heritage and Culture' (length=20)
2 => string 'Northern and Miramichi Funds' (length=28)
and so on...

Answer

Your array is an Object array, so you need the -> to access them. Using the foreach you can access the array.

foreach($items as $val){
    echo $val->name;
    echo $val->location;
    echo $val->party;
}

Try this and let me know. If anything else in the array, you need to do it similar way.