I have an api, which I send to a database and the results are returned in an xml format, this works fine and i can output the results to the screen with no problem. The xml feed is along list of property details. What i am trying to do is store the results in a mysql database, using the code below.
$feeds = array('http://web.demo.net/ademo_search.xml? &upw=123456');
foreach( $feeds as $feed ) {
$xml = simplexml_load_file($feed);
foreach($xml->channel->item as $item)
{
mysql_query("INSERT INTO property1 (id, department, branch, address1)
VALUES (
'',
'".mysql_real_escape_string($item->id)."',
'".mysql_real_escape_string($item->department)."',
'".mysql_real_escape_string($item->branch)."',
'".mysql_real_escape_string($item->address1)."')");
}
}
When I run this code I don't get an errors, nor does the data get added to the database.
here is a link to the xml structure, as you will see for my test i am only trying to insert the first few items.
This is exactly what you need :)
I hope you like it
$feed = "test.xml";
$xml = simplexml_load_file($feed);
$arr = array();
$i = 0;
foreach($xml->houses->property as $item){
$arr[$i][] = (string) $item->id;
$arr[$i][] = (string) $item->department;
$arr[$i][] = (string) $item->branch;
$arr[$i][] = (string) $item->address->address1;
$i++;
}
var_dump($arr); // now you have them in an array .. store them in db ;)
first: in the feeds array, there are a few spaces, this might cause a problem parsing the url and return 404 error or something (not sure about that, but check it)
second: in the query, remove the '' because you have 4 columns with 5 variables passed to them
third: you might want to see MySQL error by adding or die(mysql_error()) after the query before the semicolon
fourth: consider replacing mysql with mysqli or PDO
Related
I have a php file setup to pull through ONE XML data feed, What I would like to do is load up to 4 feeds into it and if possible make it select a random item too. Then parse that into an jQuery News Ticker.
My current PHP is as follows...
<?php
$feed = new DOMDocument();
$feed->load('/feed');
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$i++]['title'] = $title;
$json['item'][$i++]['description'] = $description;
$json['item'][$i++]['pubdate'] = $pubDate;
$json['item'][$i++]['guid'] = $guid;
echo '<li class="news-item">'.$title.'</li>';
}
//echo json_encode($json);
?>
How can I modify this to load more than one feed into the file?
Thanks in advance
The simplest approach to doing this is wrapping another loop around the code you have. It's not the cleanest way but will probably suffice for the purpose.
In general, IMO, it's always beneficial to learn the basics of the language first. E.g. PHP manual on foreach
This is roughly what the loop needs to look like:
$my_feeds = array("http://.....", "http://.....", "http://.....");
foreach ($my_feeds as $my_feed)
{
// This is where your code starts
$feed = new DOMDocument();
$feed->load($my_feed); <--------------- notice the variable
$json = array();
... and the rest of the code
}
this will walk through all the URLs in $my_feeds, open the RSS source, fetch all the items from it, and output them.
If I'm reading your question right, what you may want to do is turn your code into a function, which you would then run inside a foreach loop for each url (which you could store in an array or other data structure).
Edit: If you don't know much about functions, this tutorial section might help you. http://devzone.zend.com/9/php-101-part-6-functionally-yours/
I am trying to retrieve data from this XML style file :
<Product_Group>
<Product_Group_ID>131</Product_Group_ID>
<Product_Group_Title>Thanks for the Memories</Product_Group_Title>
<Products>
<On_Sale_Date>03/01/12 00:00:00.000</On_Sale_Date>
<ISBN>9780007233694</ISBN>
<Title>Thanks for the Memories</Title>
<Format>Paperback</Format>
<Sub_Format/>
<CoverImageURL_Small>http://www.harpercollins.com/harperimages/isbn/small/4/9780007233694.jpg</CoverImageURL_Small>
</Products>
</Product_Group>
I am using following code but this seems to retrieve nothing. any help in fixing this issues would be highly appreciated
$xml = simplexml_load_string($response);
//$xml= $response;
$updates = array();
//loop through all the entry(s) in the feed
for ($i=0; $i<count($xml->Product_Group); $i++)
{
//get the id from entry
$ISBN = $xml->entry[$i]->ISBN;
//get the account link
$Title = $xml->entry[$i]->Title;
//get the tweet
$Product_Group_SEO_Copy = $xml->entry[$i]->Product_Group_SEO_Copy;
}
1) It is not valid XML. What warnings do you see? You'll need to fix them for simplexml_load_string to work properly.
For example, </CoverImageURL_Small> should be <CoverImageURL_Small/>
2) Assuming that Product_Group is not your actual document root (if it is than $xml points to it already and $xml->Product_Group will not work) then you can access each element like
$xml->Product_Group->Products[$i]->ISBN;
3) It's usually simpler to use a foreach loop than a for loop when dealing with simplexml
foreach($xml->Product_Group->Products as $p)
{
$ISBN = $p->ISBN;
//var_dump($ISBN);
}
I have an XML file. I want to save all the data from the XML file to the database
The file structure of XML is like
<STORY>
<BYLINE>abc</BYLINE>
<STORYID>123456</STORYID>
</STORY>
The code for storing data to database that I am using is
$dom = new DOMDOcument();
$dom->loadXML(equitymarketnews/$zname);
$xpath = new DOMXpath($dom);
$res = $xpath->query("//STORY/");
$allres = array();
foreach($res as $node){
$result = array();
$byline = mysql_real_escape_string($node->getElementsByTagName("BYLINE")->item(0)->nodeValue);
$storyid = mysql_real_escape_string($node->getElementsByTagName("STORYID")->item(0)->nodeValue);
}
$sql12="insert into equitymarketnews values('$byline','$storyid')";
mysql_query($sql12);
I am getting nothing in my database. All values are blanks.
Where am I going wrong?
I think something is wrong with this line
$res = $xpath->query("//STORY/");
i want to story the data ie ABC and 12345 FROm XML File To Table in database
I don't really know what your question is but assuming that the code you posted does not work as you aspect, one thing i noticed is the insertion of the record:
$sql12="insert into equitymarketnews values('$byline','$storyid','$pubdate','$author','$cat','$subcat','$titleline','$subtitleline,'$storymain','$flag')";
mysql_query($sql12);
shouldn't it be inside your foreach loop? Otherwise you won't get anything into your database.
In my opinion it should look something like that:
foreach($res as $node){
$result = array();
$byline = mysql_real_escape_string($node->getElementsByTagName("BYLINE")->item(0)->nodeValue);
$storyid = mysql_real_escape_string($node->getElementsByTagName("STORYID")->item(0)->nodeValue);
$sql12="insert into equitymarketnews values('$byline','$storyid')";
mysql_query($sql12);
}
You can actually use mysql client directly for importing XML data. I do not have much experience to provide you with a code sample, but MySQL docs have quite a bit documentation on it.
Essentially, you can do something like this:
LOAD XML LOCAL INFILE 'address.xml' INTO TABLE quitymarketnews ROWS IDENTIFIED BY '<STORY>';
I'm building a script that takes the contents of several (~13) news feeds and parses the XML data and inserts the records into a database. Since I don't have any control over the structure of the feeds, I need to tailor an object operator for each one to drill down into the structure in order to get the information I need.
The script works just fine if the target node is one step below the root, but if my string contains a second step, it fails ( 'foo' works, but 'foo->bar' fails). I've tried escaping characters and eval(), but I feel like I'm missing something glaringly obvious. Any help would be greatly appreciated.
// Roadmaps for xml navigation
$roadmap[1] = "deal"; // works
$roadmap[2] = "channel->item"; // fails
$roadmap[3] = "deals->deal";
$roadmap[4] = "resource";
$roadmap[5] = "object";
$roadmap[6] = "product";
$roadmap[8] = "channel->deal";
$roadmap[13] = "channel->item";
$roadmap[20] = "product";
$xmlSource = $xmlURL[$fID];
$xml=simplexml_load_file($xmlSource) or die(mysql_error());
if (!(empty($xml))) {
foreach($xml->$roadmap[$fID] as $div) {
include('./_'.$incName.'/feedVars.php');
include('./_includes/masterCategory.php.inc');
$test = sqlVendors($vendorName);
} // end foreach
echo $vUpdated." records updated.<br>";
echo $vInserted." records Inserted.<br><br>";
} else {
echo $xmlSource." returned an empty set!";
} // END IF empty $xml result
While Fosco's solution will work, it is indeed very dirty.
How about using xpath instead of object properties?
$xml->xpath('deals/deal');
PHP isn't going to magically turn your string which includes -> into a second level search.
Quick and dirty hack...
eval("\$node = \"\$xml->" . $roadmap[$fID] . "\";");
foreach($node as $div) {
My first attempt at retrieving data from XML for a maps application has failed. Here is a piece of the XML Feed.
<?xml version="1.0" encoding="UTF-8"?>
<DirectionsResponse>
<status>OK</status>
<route>
<leg>
<start_address>Winkfield, Bracknell, Berkshire RG42 6LY, UK</start_address>
<end_address>Wentworth, Surrey GU25 4, UK</end_address>
</leg>
</route>
</DirectionsResponse>
I want to get the start and end address and return them via AJAX to the application.
The PHP
<?php
$start = $_POST['start'];
$end = $_POST['end'];
$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$end.'&sensor=false');
// data to fetch
$start = $xml->xpath("/DirectionsResponse/route/leg/start_address");
$end = $xml->xpath("/DirectionsResponse/route/leg/end_address");
$start = array($start);
// output
echo json_encode( array('output'=>$start[0]));
?>
Annoyingly this is returning an object to the page.
Response :: {"output":[{"0":"Winkfield, Windsor, Berkshire SL4 2ES, UK"}]}
Anyone know how to stop that from happening. I just want the value Winkfield, Windsor, Berkshire SL4 2ES, UK.
Haven't tested your specific case, but i remember running into something similar when using SimpleXML, you might want to use (string) to cast it out of the object
array('output'=> (string)$start[0])
Or rather just leave out $start = array($start) and just do
array('output'=> (string)$start)
On reading the SimpleXML XPath documentation (http://www.php.net/manual/en/simplexmlelement.xpath.php) again i think your problem might be this:
Returns an array of SimpleXMLElement objects or FALSE in case of an error.
So the XPath returns an array, then you wrap that in an array and take the first element of that array, so all you end up with is the original array - remove the array wrap and you should be fine
function XMLReader()
{
$MyArray = array();
$doc = new DOMDocument();
$doc->load( 'XMLFilePath.xml' );
$info = $doc->getElementsByTagName( "leg" );
foreach( $info as $Type )
{
$details = $Type->getElementsByTagName( "start_address" );
$detail = $details->item(0)->nodeValue;
$MyArray [] = $detail;
}
return $MyArray;
}
and same for end_Address.
I wish this answer is helpful.
Just echo $start? Also, why do you make an array of start and then output the first element, it doesnt make any sense at all.
echo $xml->route->leg->start_address;
This is the edited answer. I checked it. Its working properly on the XML.