Page 1 of 1

PHP Not Reading XML Feed Correctly

Posted: Thu Oct 20, 2005 9:06 am
by neilmunn
I just aboout finished writing a script to import an XML feed into a MySQL database. The script pharses the XML and inserts into the database fine.

The feed that I am using contains about 200 articles, but no matter what I do I can only read the last article into the database. How do I go about looping the script to read every article?

Any help would be appreciated.

Cheers
-Neil

Code: Select all

<?php

include ("financeshop/include/site_config.php");
include ("financeshop/include/dbconnect.php");

$type_SQL = "SELECT * FROM xmlfeed";
//@debug("SQL: " . $type_SQL);
$type_Query = mysql_query($type_SQL);

if (!$type_Query) {
//@debug("ERROR: " . mysql_error());
} else {
    $type_RS = mysql_fetch_assoc($type_Query);
    $typeTitle = $type_RS['type'];
}

if (!$_GET['type']) {
    $_GET['type'] = 'all';
}

$file = "http://feeds.directnews.org.uk/?49871849-a276-4a12-b047-bec260ced467";
$feed = array();
$key = "";
$info = "";

function startTag($parser, $name, $attrs)
{
	global $stack;
  $tag = array("name" => $name,"attributes" => $attrs);
  array_push($stack,$tag);
}

function cdata($parser, $cdata)
{
	global $stack;
  if(trim($cdata))
  {
    $stack[count($stack) - 1]['cdata'] = $cdata;
  }
}

function endTag($parser, $name)
{
  global $stack;
  $stack[count($stack) - 2]['children'][] = $stack[count($stack) - 1];
  array_pop($stack);
}

function startElement($xml_parser,  $attrs )
{
  global $feed;
}

function endElement($xml_parser, $name)
{
  global $feed,  $info;
  $key = $name;
  $feed[$key] = $info;
  $info = "";
}

function charData($xml_parser, $data )
{
  global $info;
  $info .= $data;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "charData");
$fp = fopen($file, "r");
while ($data = fread($fp, 8192))
!xml_parse($xml_parser, $data, feof($fp));
xml_parser_free($xml_parser);

$sql= "INSERT INTO `xmlfeed` ( `";
$j=0;
$i=count($feed);
foreach( $feed as $assoc_index => $value )
  {
  $j++;
  $sql.= strtolower($assoc_index);
  if($i>$j) $sql.= "` , `";
  if($i<=$j) {$sql.= "` ) VALUES ('";}
  }
 $h=0;
foreach( $feed as $assoc_index => $value )
  {
  $h++;
  $sql.= utf8_decode(trim(addslashes($value)));
  if($i-1>$h) $sql.= "', '";
  if($i<=$h) $sql.= "','')";
  }
  $sql=trim($sql);

  echo $sql;  // Displays what is happening on screen. Remove when finished.
  $result = mysql_query($sql,$cn);

?>