Hello, I am learning php/rss but am confused by this. When I just echo out the array, all of the data shows up on the page, but when I do a loop to insert each row into mysql, it only inserts the last item from the xml. Can someone explain this to me? <?php $con = mysql_connect("someserver.net","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("rss", $con); $feedURL = 'http://www.nytimes.com/services/xml/rss/nyt/Magazine.xml'; $doc = new DOMDocument(); $doc->load($feedURL); $arrFeeds = array(); foreach ($doc->getElementsByTagName('item') as $node) { $itemRSS = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue ); array_push($arrFeeds, $itemRSS); //print_r($arrFeeds); foreach($arrFeeds as $arrItem) { //echo $arrItem[title]; //echo "<br />"; //echo $arrItem[desc]; //echo $arrItem[date]; $sql="INSERT INTO address_book (email) VALUES ('$arrItem[title]')"; } } if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> Code (markup):
I see the problem, you are creating your sql string within the loop but trying to run the SQL string outside of the loop. updated code below.... <?php $con = mysql_connect("someserver.net","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("rss", $con); $feedURL = 'http://www.nytimes.com/services/xml/rss/nyt/Magazine.xml'; $doc = new DOMDocument(); $doc->load($feedURL); $arrFeeds = array(); foreach ($doc->getElementsByTagName('item') as $node) { $itemRSS = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue ); array_push($arrFeeds, $itemRSS); //print_r($arrFeeds); foreach($arrFeeds as $arrItem) { //echo $arrItem[title]; //echo "<br />"; //echo $arrItem[desc]; //echo $arrItem[date]; $sql="INSERT INTO address_book (email) VALUES ('$arrItem[title]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } } } mysql_close($con); ?> PHP: