Posted by Elizabeth Smith on 10/01/02 11:11
Yashesh Bhatia wrote:
> hi! i'm trying to use the simple_xml functions to get an arrray of
> data from a sample xml file.
>
> here's my sample_data.xml
> --------------------------------------------------------------------------------------------
>
> <?xml version="1.0" encoding="ISO-8859-1"?>
> <sample_data>
> <first_names>
> <first_name>amit</first_name>
> <first_name>amar</first_name>
> </first_names>
> </sample_data>
> --------------------------------------------------------------------------------------------
>
> the php file
> --------------------------------------------------------------------------------------------
>
> <?php
> $sample_data = simplexml_load_file("sample_data.xml");
> print_r($sample_data);
> print_r($sample_data->first_names);
> print_r($sample_data->first_names->first_name);
> ?>
> --------------------------------------------------------------------------------------------
>
> output of "$ php test_xml_1.php"
> --------------------------------------------------------------------------------------------
>
> SimpleXMLElement Object
> (
> [first_names] => SimpleXMLElement Object
> (
> [first_name] => Array
> (
> [0] => amit
> [1] => amar
> )
>
> )
>
> )
> SimpleXMLElement Object
> (
> [first_name] => Array
> (
> [0] => amit
> [1] => amar
> )
>
> )
> SimpleXMLElement Object
> (
> [0] => amit
> )
> --------------------------------------------------------------------------------------------
>
>
> The above output shows $sample_data->first_names->first_name as an
> ARRAY in the first 2 print_r 's however when a print_r is run on
> itself it shows it as a SimpleXMLElementObject.
> Question is why the last print_r gives different information
> compared to the other 2.
>
> I also tried running
> $key = array_rand($sample_data->first_names->first_name)
>
> and it gives a warning message
> "Warning: array_rand(): First argument has to be an array in
> /home/yvb/work/practice/php/XML/foo.php on line 16"
>
> any clue how do i use the
> $sample_data->first_names->first_name as an array ?
>
> thx.
>
> yashesh.
>
>
That's how print_r displays objects and nested objects - try a var_dump
on the item and you'll see that simplexml does NOT return arrays but
instead returns simplexml objects - if you want to use array_rand you
can cast
(http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting)
the object to an array, or check out the user notes on simplexml
http://us2.php.net/manual/en/ref.simplexml.php
to find example functions to change a simplexml object to an array
personally I prefer dom and use a domtoarray function - but YMMV -
please read the simplexml documentation again, it returns objects
(nested ones) NOT arrays
[Back to original message]
|