Hello,
This should be pretty easy for someone to fix. I just started playing around with the xml parsing functions in php when I ran in to a lil problem... If the $curTag finds an element that is empty, it wont record it to the array.
Here is the code:
<?php
class xItem {
var $xTitle;
var $xDescription;
}
// general vars
$sTitle = "";
$sDescription = "";
$arItems = array();
$itemCount = 0;
// ********* Start User-Defined Vars ************
// xml url goes here
$uFile = "myxmlfile.xml";
// ********* End User-Defined Vars **************
function startElement($parser, $name, $attrs) {
global $curTag;
$curTag .= "^$name";
}
function endElement($parser, $name) {
global $curTag;
$caret_pos = strrpos($curTag,'^');
$curTag = substr($curTag,0,$caret_pos);
}
function characterData($parser, $data) { global $curTag;
// now get the items
global $arItems, $itemCount;
$itemTitleKey = "^ITEMS^ITEM^TITLE";
$itemDescKey = "^ITEMS^ITEM^DESC";
if ($curTag == $itemTitleKey) {
// make new xItem
$arItems[$itemCount] = new xItem();
// set new item object's properties
$arItems[$itemCount]->xTitle = $data;
}
elseif ($curTag == $itemDescKey) {
$arItems[$itemCount]->xDescription = $data;
// increment item counter
$itemCount++;
}
}
// main loop
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($uFile,"r"))) {
die ("could not open RSS for input");
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
// write out the items
?>
<html>
<head>
<title>test</title>
</head>
<body bgcolor = "#FFFFFF">
<br>
<?php
for ($i=0;$i<count($arItems)-1;$i++) {
$txItem = $arItems[$i];
?>
<b><?php echo($txItem->xDescription); ?></b>
<br>
<img src="<?php echo ($txItem->xTitle); ?>">
<br>
<?
}
?>
</body>
</html>
xml structure:
<?xml version="1.0" encoding="iso-8859-1"?>
<items>
<item>
<title>Some Title</title>
<desc>Some Desc</desc>
</item>
</items>
So basically, if I have the all the desc fields with data it will build fine. If the DESC node is empty... it omits it from the array all together.
Can anyone point me in the right direction?
Thanks for your time 🙂