I recently wrote a little function that parses an xml file one-level deep and returns an object with property->value pairs:
// An empty shell for housing an xml response.
class XMLResponse {}
function ParseXmlFile($FileLocation) {
$Lines = file($FileLocation);
$XML = new XMLResponse();
// Loop through each of the lines of the response and get the
// properties/values
for ($i = 0; $i < count($Lines); $i++) {
$Matches = false;
preg_match("/(<([^<>\s]*)(\s[^<>]*)?>)(.+?)(<([^<>\s]*)(\s[^<>]*)?>)/",
$Lines[$i],
$Matches);
if (count($Matches) == 7) {
$Property = $Matches[2];
$Value = $Matches[4];
$XML->$Property = $Value;
}
}
return $XML;
}
}
/* Assuming the xml file contains something like this:
<root>
<status>ok</status>
<id>123456</id>
<username>marky</username>
</root>
*/
$MyXml = ParseXmlFile("/path/to/my/xml/file.xml");
echo($MyXml->username." has an id of ".$MyXml->id." and has a status of ".$MyXml->status);
/*
Will Print:
marky has an id of 123456 and has a status of ok
*/
Does the XML have to be in any specific format?
if not, it could literally be a textdump of the option tags you need, provided it conformed to xml rules.
PS. Once I've got this working I need to somehow turn it into a Wordpress extension so that you can automatically insert a link into a post that points to one of the album ids. But that's a post for the Wordpress forum methinks!
Comments
// An empty shell for housing an xml response. class XMLResponse {} function ParseXmlFile($FileLocation) { $Lines = file($FileLocation); $XML = new XMLResponse(); // Loop through each of the lines of the response and get the // properties/values for ($i = 0; $i < count($Lines); $i++) { $Matches = false; preg_match("/(<([^<>\s]*)(\s[^<>]*)?>)(.+?)(<([^<>\s]*)(\s[^<>]*)?>)/", $Lines[$i], $Matches); if (count($Matches) == 7) { $Property = $Matches[2]; $Value = $Matches[4]; $XML->$Property = $Value; } } return $XML; } } /* Assuming the xml file contains something like this: <root> <status>ok</status> <id>123456</id> <username>marky</username> </root> */ $MyXml = ParseXmlFile("/path/to/my/xml/file.xml"); echo($MyXml->username." has an id of ".$MyXml->id." and has a status of ".$MyXml->status); /* Will Print: marky has an id of 123456 and has a status of ok */
<?xml version="1.0" encoding="UTF-8"?> <gallery> <album id="flowers" title="" description="Photos of flowers"> /> </album> <album id="cars" title="" description="Photos of cars"> /> </album> <album id="animals" title="" description="Photos of erm, animals"> /> </album> </gallery>