Jump to content

help with parsing from array to database


randomsai

Recommended Posts

<?PHP

HEADER('content-type: text/plain');

 

// define hooks to rss_parser class as xml functions do not allow object methods as handlers.

FUNCTION rss_start_element($parser, $name, $attributes) {

  GLOBAL $rss;

  $rss->start_element($parser, $name, $attributes);

}

 

FUNCTION rss_end_element($parser, $name) {

  GLOBAL $rss;

  $rss->end_element($parser, $name);

}

 

FUNCTION rss_character_data($parser, $data) {

  GLOBAL $rss;

  $rss->character_data($parser, $data);

}

 

 

CLASS rss_parser {

 

// constructor. setup parser options and handlers.

FUNCTION rss_parser() {

  $this->error = '';

  $this->file = '';

 

  $this->channel = ARRAY();

  $this->data = '';

  $this->stack = ARRAY();

  $this->num_items = 0;

 

  $this->xml_parser = XML_PARSER_CREATE();

  XML_SET_ELEMENT_HANDLER($this->xml_parser, "rss_start_element", "rss_end_element");

  XML_SET_CHARACTER_DATA_HANDLER($this->xml_parser, "rss_character_data");

}

 

FUNCTION character_data($parser, $data) {

  IF (EMPTY($this->data)) $this->data = TRIM($data);

  ELSE $this->data .= ' '.TRIM($data);             

}

 

FUNCTION start_element($parser, $name, $attrs) {

  SWITCH($name) {

    CASE 'RSS':

      BREAK;

 

    CASE 'CHANNEL':

      BREAK;

 

 

    CASE 'ITEM':

      ARRAY_PUSH($this->stack, $name);

      ARRAY_PUSH($this->stack, $this->num_items); // push item index.

      $this->item[$this->num_items] = ARRAY();

      $this->num_items++;

      BREAK;

 

    CASE 'TEXTINPUT':

      ARRAY_PUSH($this->stack, $name);

      BREAK;

 

    DEFAULT:

      ARRAY_PUSH($this->stack, $name);

      BREAK;

 

  } 

}

 

FUNCTION end_element($parser, $name) {

  SWITCH ($name) {

    CASE 'RSS':

      BREAK;

 

    CASE 'CHANNEL':

      BREAK;

 

 

    CASE 'ITEM':

      ARRAY_POP($this->stack);

      ARRAY_POP($this->stack);

      BREAK;

 

    CASE 'TEXTINPUT':

      ARRAY_POP($this->stack);

      BREAK;

 

    DEFAULT: // child element.

      $element = (IMPLODE("']['",$this->stack));     

      EVAL("\$this->channel['$element']=\$this->data;"); // this does all the hard work.

      ARRAY_POP($this->stack);

      $this->data = '';

      BREAK;

  }

}

 

 

 

FUNCTION parse() {

  IF (!($fp = @FOPEN($this->file, "r"))) {

    $this->error = "Could not open RSS source \"$this->file\".";

    RETURN FALSE;

  }

  WHILE ($data = FREAD($fp, 4096)) {

    IF (!XML_PARSE($this->xml_parser, $data, FEOF($fp))) {

      $this->error = SPRINTF("XML error: %s at line %d.",

        XML_ERROR_STRING(XML_GET_ERROR_CODE($this->xml_parser)),

        XML_GET_CURRENT_LINE_NUMBER($this->xml_parser));

      RETURN FALSE;

    }

  }

  XML_PARSER_FREE($this->xml_parser);

  RETURN TRUE;

}

 

 

 

$rss = NEW rss_parser();

$rss->file = 'http://www.trinidadnews.net/rss.php';

$rss->parse() or DIE($rss->error);

IF ($rss->error) PRINT $rss->error;

 

PRINT_R($rss->channel);

 

$con = mysql_connect("localhost", "root", "");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

 

mysql_select_db("trinidadnews", $con);

 

mysql_query("INSERT INTO news (headline, description, date)

VALUES ()");

 

mysql_close($con);

 

 

?>

 

 

 

 

 

the output looks like this:

 

Array

(

    [TITLE] => Trinidad News latest RSS headlines - Trinidad News.Net

    [DESCRIPTION] => Provides the latest RSS feeds for Trinidad News. For more headlines on Breaking, National, Business, Finance, Sports and World News, visit our home page

    [COPYRIGHT] => Trinidad News.Net

    [LINK] => http://www.trinidadnews.net/

    [LANGUAGE] => en-us

    [PUBDATE] => Sun, 03 Jan 2010 18:30:20 -0500

    [LASTBUILDDATE] => Sun, 03 Jan 2010 18:30:20 -0500

    [TTL] => 30

    [iTEM] => Array

        (

            [0] => Array

                (

                    [TITLE] => Shops closed but New Year shopping steady

                    [DESCRIPTION] => While many stores at Excellent City Centre, Town Centre and other main shopping malls in the heart of Port-of-Spain, opted not to open their doors for business after the start of the new year, it was ...

                    [LINK] => http://feeds.trinidadnews.net/?rid=30996601 & cat=f7da47955ef03229

                    [PUBDATE] => Sun, 03 Jan 2010 02:26:32 -0500

                    [sOURCE] => Newsday

                    [GUID] => http://feeds.trinidadnews.net/?rid=30996601 & cat=f7da47955ef03229

                )

 

            [1] => Array

                (

                    [TITLE] => Couva officers want probe into free-spending cop

                    [DESCRIPTION] => Concerns are being raised by police officers at the Couva Police Station regarding the investigation into the disappearance of US$94,000 from the property room of the station.

                    [LINK] => http://feeds.trinidadnews.net/?rid=30995597 & cat=f7da47955ef03229

                    [PUBDATE] => Sun, 03 Jan 2010 01:05:44 -0500

                    [sOURCE] => Newsday

                    [GUID] => http://feeds.trinidadnews.net/?rid=30995597 & cat=f7da47955ef03229

                )

 

 

i want to get the title , description and date into my database but i cant seem to get the varialbes to store it to the data base

 

please help

<?php
mysql_query("INSERT INTO news (headline, description, date)
VALUES ()");
?>

 

you need to make it add the values from the $rss->channel object in the SQL query. Something like:

 

<?php
if (!mysql_query("INSERT INTO news (headline, description, date)
VALUES (".$rss->channel['ITEM']['TITLE'].")"))
  print('Could not insert data into database. Error given: '.mysql_error().'<br/>');
?>

 

I don't know if the variable naming is correct because i haven't used objects much.

ok well i have to get rss feeds from weather and news sites and store them in a database, i just dont know how lol,

can you think of a way that for each title, description, and date, i could store each headline ( for news), in the database under the respective heading?

yeah... make a table with fields title, descripton, date etc. whatever you want, and then use PHP to fetch the RSS and put it in the database.

 

here's a page I use for quick reference of MYSQL syntax and commands: http://www.bios.niu.edu/johns/bioinform/mysql_commands.htm

 

i dont know how to get data from RSS feeds with php - never tried it, but your original code for the SQL insertion was close, you just have to build the SQL INSERT query correctly and have php send the query and check it inserted correctly. Because I don't use OOP model in my own php code I am not familiar enough with the syntax in your code to give you an exact code sample. If you're using OOP you should surely be able to work it out.

ok thanks, but for me to enter data into my daabase i would need variables, rite? but from my parser, i dont have specific variables assigned to each field, eg title, description or date. that is why i converted the parser to an array form so that i could enter the data to the database, but i cant seem to locate where the variables are being stored, or if there are being stored in a tempeorary variable.

This is the contents of $rss->channel which is an array.

 

[pre]

Array

(

    [TITLE] => Trinidad News latest RSS headlines - Trinidad News.Net

    [DESCRIPTION] => Provides the latest RSS feeds for Trinidad News. For more headlines on Breaking, National, Business, Finance, Sports and World News, visit our home page

    [COPYRIGHT] => Trinidad News.Net

    [LINK] => http://www.trinidadnews.net/

    [LANGUAGE] => en-us

    [PUBDATE] => Sun, 03 Jan 2010 18:30:20 -0500

    [LASTBUILDDATE] => Sun, 03 Jan 2010 18:30:20 -0500

    [TTL] => 30

    [iTEM] => Array

        (

         

 

    * => Array

 

 

                (

                    [TITLE] => Shops closed but New Year shopping steady

                    [DESCRIPTION] => While many stores at Excellent City Centre, Town Centre and other main shopping malls in the heart of Port-of-Spain, opted not to open their doors for business after the start of the new year, it was ...

                    [LINK] => http://feeds.trinidadnews.net/?rid=30996601 & cat=f7da47955ef03229

                    [PUBDATE] => Sun, 03 Jan 2010 02:26:32 -0500

                    [sOURCE] => Newsday

                    [GUID] => http://feeds.trinidadnews.net/?rid=30996601 & cat=f7da47955ef03229

                )

 

            [1] => Array

                (

                    [TITLE] => Couva officers want probe into free-spending cop

                    [DESCRIPTION] => Concerns are being raised by police officers at the Couva Police Station regarding the investigation into the disappearance of US$94,000 from the property room of the station.

                    [LINK] => http://feeds.trinidadnews.net/?rid=30995597 & cat=f7da47955ef03229

                    [PUBDATE] => Sun, 03 Jan 2010 01:05:44 -0500

                    [sOURCE] => Newsday

                    [GUID] => http://feeds.trinidadnews.net/?rid=30995597 & cat=f7da47955ef03229

                )

[/pre]

 

are you saying that all of the key names in that array varies with each rss read you do? If it doesn't or even if it does, surely you can make it look through the key names in the array and pull out ones that look like what you want.

 

I'm not sure about how to access the array elements of the $rss->channel property since i dont use oop much in php but I'd imagine you could do something like:

 

$infoArray = $rss->channel;

 

then work on the values inside $infoArray. Example:

print($infoArray['ITEM'][1]['TITLE']);

 

should output: Couva officers want probe into free-spending cop

 

Just change the array key names to get the data you want or need.

it did work , thank you, but yet again another problem, lol.

i am now trying to put in inthe database via

 

mysql_query("INSERT INTO news (headline)

 

VALUES ('$infoArray['ITEM'][1]['TITLE']')");

 

but this doesn't seem to work, currently i am trying to find a way to do it, and came across the implode funtion.

any help would be deeply appreciated, thanks

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.