Forum Moderators: coopster

Message Too Old, No Replies

Import XML to PHP array

         

cantona

4:39 pm on Mar 16, 2009 (gmt 0)

10+ Year Member



Hello

I want to reference an external XML file in my PHP, and then display some of the nodes.

It's only a simple XML structure with one (maybe 2) child nodes.

I was thinking of using file_get_contents() to import the XML... but then do I need some sort of parser to enable PHP to display bits of it.

Has anyone got any simple examples of this? Or maybe something using zend_framework ?

Regards

eeek

10:01 pm on Mar 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Take a look at the Simple XML feature"

[php.net...]

cantona

11:36 am on Mar 17, 2009 (gmt 0)

10+ Year Member



Thanks this is just what I needed

cantona

4:21 pm on Mar 17, 2009 (gmt 0)

10+ Year Member



I have this working now, but if I want to cache it I run into problems.

I want to serialize the array and store it in a text file. But I don't think you can serialize a SimpleXML object (well, it breaks, so I'm guessing you can't).

What's the best practice for caching a SimpleXML object (doesn't have to be 'the object' just part of it).

Currently I have..........


$url = "http://www.domain.com/users/file.xml";
$xml = simplexml_load_string(file_get_contents($url));
$friends = $xml->friends_count;
$updates = $xml->statuses_count;

$data_array[] = array(
'friends' => $friends,
'updates' => $updates,
);

$data_array_s = serialize($data_array);
$handle = fopen("/tmp/cache.txt","w");
fwrite($handle,$data_array_s);
fclose($handle);

# if the cache file has expired, I unserialize the array with...
$data_array = unserialize(file_get_contents("/tmp/cache.txt"));
var_dump($data_array);

# which displays as
...
'Friends' =>
object(SimpleXMLElement)[23]
string '1130' (length=4)
...

How can I use that Friends object. I just want to use it as a string and display it! $data_array['Friends'] doesnt work


Thanks

cantona

9:29 am on Mar 18, 2009 (gmt 0)

10+ Year Member



Solution:

You cannot serialize SimpleXML objects.

To get around this:

1) For each object, instead of

$friends = $xml->friends_count; 
do
 $friends = $xml->friends->asXML(); 

2) Then serialize as before

3) After unserializing the array, the XML will still have tags. If not wanted, run

strip_tags()
.

Now I can cache SimpleXML elements.

whoisgregg

3:23 pm on Mar 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm glad to see you got it sorted, cantona. Thanks for posting your solution. :)