Forum Moderators: coopster

Message Too Old, No Replies

parsing xml using php/expat

         

xentsear

8:16 am on Aug 5, 2003 (gmt 0)

10+ Year Member



I have this xml file :
<item>
<name>mypicture</name>
<id>1234567</id>
<type>gif</type>
</item>
<item>
<name>mypicture2</name>
<id>1234568</id>
<type>jpg</type>
</item>

I am able to parse the entire xml using expat and print using php. However, i am not able to maniplate the data inside the tags with variables. For example, if i cant construct a url to retrieve the image that resides in my webserver. Any idea how i might be able to do that?

Timotheos

6:33 pm on Aug 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here's an example I've used just to get you going. I'm assuming you've set your element and data handle functions all ready. The trick is to have a global variable across the functions to handle the current tag. Now you can put code into any of the functions to handle your data.

$currentTag = "";
$picture = array();

function startElement($parser, $name, $attrs) {
global $currentTag;
$currentTag = $name;
}

function endElement($parser, $name) {
global $currentTag;
// clear current tag variable
$currentTag = "";
}

// process data between tags
function characterData($parser, $data) {

global $currentTag;
global $picture;

switch ($currentTag) {
case "name":
$picture['name'] = $data;
break;
case "id":
$picture['id'] = $data;
break;
case "type":
$picture['type'] = $data;
break;
default:
break;
}
}

vincevincevince

6:42 pm on Aug 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




<?php
$xml="
<item>
<name>mypicture</name>
<id>1234567</id>
<type>gif</type>
</item>
<item>
<name>mypicture2</name>
<id>1234568</id>
<type>jpg</type>
</item>
";
$xml=preg_replace("/\n/"," ",$xml);
while (preg_match("/^[^\<]*\<item\>[^\<]*\<name\>([^\<]*)\<\/name\>[^\<]*\<id\>([^\<]*)\<\/id\>[^\<]*\<type\>([^\<]*)\<\/type\>[^\<]*\<\/item\>/",$xml,$matches))
{
echo "<a href=\"".htmlentities("http://example.foo/images/$matches[1].$matches[3]")."\">Image ID $matches[2]</a><br>";
$xml=substr($xml,strpos($xml,"</item>")+9);
}
?>