I have an ecommerce website in which regularly transactions keeps happening. Now we are developing an android app for the same. So I was asked to build an API using PHP. The API that i made was in xml format. But now since i will be sending he login credentials through it I am scared that someone would hack it. So can someone help me with it.
here is the way i had created the xml API using php..
<?php
include 'config.php';
include 'database.php';
$sqlCat = "select category_id,image,name from table" ;
$categories = DatabaseHandler::GetAll($sqlCat);
$xml = new DomDocument("1.0","UTF-8");
$content = $xml->createElement("content");
$content = $xml->appendChild($content);
foreach($categories as $category) {
$item = $xml->createElement("item");
$catName = $xml->createElement("catName",htmlspecialchars($category['name']));
$catName = $item->appendChild($catName);
$catImage = $xml->createElement("catImage",htmlspecialchars($category['image']));
$catImage = $item->appendChild($catImage);
$sql = "select image,name,model,price,quantity from table;
$results = DatabaseHandler::GetAll($sql);
foreach($results as $key=>$result) {
$product = $xml->createElement("product");
$product->setattribute('id',$key);
$model = $xml->createElement("model",$result['model']);
$model = $product->appendChild($model);
$name = $xml->createElement("name",htmlspecialchars($result['name']));
$name = $product->appendChild($name);
$image = $xml->createElement("image",htmlspecialchars($result['image']));
$image = $product->appendChild($image);
$price = $xml->createElement("price",$result['price']);
$price = $product->appendChild($price);
$product = $item->appendChild($product);
}
$item = $content->appendChild($item);
}
$xml->FormatOutput = true;
$output = $xml->saveXML();
$xml->save("categories.xml");
?>
and I get the xml in this form..
<content>
<item>
<catName>Comp</catName>
<catImage/>
<product id="0">
<model>156443</model>
<name>CD</name>
<image>109.jpg</image>
<price>48</price>
</product>
<product id="1">
<model>46876</model>
<name>memory card</name>
<image>81.jpg</image>
<price>12</price>
</product>
<product id="2">
<model>865793</model>
<name>drive</name>
<image>51.png</image>
<price>2</price>
</product>
</item>
</content>
Can someone tell whether the way i have generated API in XML format correct.
Dont make think too complex make it simple like following code
$con = mysql_connect("localhost","root","root") or die("could not connect".mysql_error());
//select your database table
mysql_select_db("android_maps", $con) or die("Could not select database".mysql_error());
//get your results with a mysql query
$result = mysql_query("SELECT gmaps.*, urls.* FROM gmaps, urls WHERE urls.idgmaps = gmaps.idgmaps") or die(mysql_error());
//run a while loop get your data.
while($location = mysql_fetch_array($result)) {
$output = '<?xml version="1.0" encoding="utf-8"?>';
$output .= '<data>';
$output .= "<lat>".$location['lat']."</lat>";
$output .= "<long>.".$location['lon']."</long>";
$output .= "<description>.".$location['description']."</description>";
$output .= '</data>';
print $output;
}
mysql_close($con);
}else{
echo "<h1>No results to show for you query</h1>";
}
for more info
http://teachingyou.net/php/php-api-development-dreaming-of-your-own-api-make-it-possible-today/
Related
I have a problem with simpleXML and variable
$num = $categorie['id'];
echo $num; /*return value is 1 or 0*/
$fav = $xml->categorie[$num]->addChild("fav"," ");
I want to put $num in categorie[$num] but not work. How i can do this?
My XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
<categorie id="0" name="Search">
<fav>
<link>Google</link>
<desc>www.google.fr</desc>
</fav>
<fav>
<link>Orange</link>
<desc>www.orange.fr</desc>
</fav>
</categorie>
<categorie id="1" name="Social">
<fav>
<link>Facebook</link>
<desc>www.facebook.com</desc>
</fav>
<fav>
<link>Youtube</link>
<desc>www.youtube.com</desc>
</fav>
</categorie>
</data>
MY php complete php code. And the problem is in the foreach loop. i compare the categorie name to get the id and put the new favorite in the correct categorie.
<?php
$link = $_POST['link'];
$desc= $_POST['desc'];
$cat = $_POST['cat'];
$xml = simplexml_load_file('../data/data.xml');
foreach($xml->categorie as $categorie)
{
if (strcmp($categorie['name'], $cat) == 0)
{
$num = $categorie['id'];
echo $num;
$fav = $xml->categorie[$num]->addChild("fav"," ");
$fav->addChild("link", $link);
$fav->addChild("desc", $desc);
$xml->asXML('../data/data.xml');
}
}
?>
Thanks
The solution is to convert an object to integer with intval()
$num = intval($categorie['id']);
$fav = $xml->categorie[$num]->addChild("fav"," ");
$fav->addChild("link", $link);
$fav->addChild("desc", $desc);
$xml->asXML('../data/data.xml');
I have the following example XML:
<PRODUCTRATINGLIST>
<PRODUCT>
<VENDORREF>AC308A~</VENDORREF>
<RATING>100%</RATING>
<REVIEWCOUNT>7</REVIEWCOUNT>
</PRODUCT>
<PRODUCT>
<VENDORREF>AC308C~</VENDORREF>
<RATING>98%</RATING>
<REVIEWCOUNT>89</REVIEWCOUNT>
</PRODUCT>
</PRODUCTRATINGLIST>
I'm simply trying to extract each node under PRODUCT:
$ratings = simplexml_load_file("test.xml");
foreach ($ratings->PRODUCT as $rating){
$part = $rating->VENDORREF;
$rating = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;
}
If I then try to print each element e.g.
echo $part.' '.$rating.' '.$numReviews;
$numReviews is always blank and I have no idea why.
You are replacing the $rating array with a variable, fix it like this:
$part = $rating->VENDORREF;
$rating_string = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;
Check below code. You change the variable names.
$ratings = simplexml_load_file("test.xml");
foreach ($ratings->PRODUCT as $rating){
$part = $rating->VENDORREF;
$ratingVal = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;
}
echo $part.' '.$ratingVal.' '.$numReviews;
Inside a DDBB a have the following data:
SELECT `addedat`, `catname`, `catkey` FROM `categorias`;
"2014-06-23" "Complementos" "complementos"
"2014-06-23" "Hombre" "hombre"
"2014-06-23" "Mujer" "mujer"
"2014-06-23" "Niños y bebes" "niños_y_bebes"
Got the following function script:
public function listAllCategories(){
$ret = null;
$result = self::$ddbb->executeQuery(self::$dao->getQueryGetAllCategories());
if ($result && (mysql_num_rows($result) !== 0)){
$categories = array();
while($row = mysql_fetch_row($result)){
$aux = new Categoria();
$aux->setCatDate($row[0]);
$aux->setCatName($row[1]);
$aux->setCatKey($row[2]);
array_push($categories, $aux);
}//while
mysql_free_result($result);
$ret1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$ret1 .= "\n<categories>";
foreach($categories as $category){
$ret1 .= "\n\t<category>";
$ret1 .= "\n\t\t<addedat>".$category->getCatDate()."</addedat>";
$ret1 .= "\n\t\t<name>".$category->getCatName()."</name>";
$ret1 .= "\n\t\t<key>".$category->getCatKey()."</key>";
$ret1 .= "\n\t</category>";
}//foreach
$ret1 .= "\n</categories>";
$ret = trim($ret1);
}else{
$ret = new Error(self::$errorFilePath, "ERROR: no se pudo listar las categorias. MySQL = ".self::$ddbb->getError());
}
return $ret;
}
After this function, a super 'controller.php' do the following:
header("Content-Type", "text/xml");
header_response_code(200);
echo $ret;
But the script returns the following XML file:
<?xml version="1.0" encoding="UTF-8"?>
<categories>
<category>
<addedat>2014-06-23</addedat>
<name>Niños y bebes</name>
<key>niños_y_bebes</key>
</category>
<category>
<addedat>2014-06-23</addedat>
<name>Niños y bebes</name>
<key>niños_y_bebes</key>
</category>
<category>
<addedat>2014-06-23</addedat>
<name>Niños y bebes</name>
<key>niños_y_bebes</key>
</category>
<category>
<addedat>2014-06-23</addedat>
<name>Niños y bebes</name>
<key>niños_y_bebes</key>
</category>
</categories>
And jQuery claims Invalid XML
You should use a library that can encode strings into XML properly like SimpleXML instead of doing string concatenations:
$ret = new SimpleXMLElement('<categories/>');
foreach ($categories as $category) {
$category = $ret->addChild('category');
$category->addedat = $category->getCatDate();
$category->name = $category->getCatName();
$category->key = $category->getCatKey();
}
$ret->asXML('php://output');
The only precondition for this to work is that teh getters of $category (that are the methods like $category->getCatDate()) are returning UTF-8 encoded strings.
If they don't you'll see errors - but you'll see them early. See as well:
How to get useful error messages in PHP?
and ensure you've got error logging enabled so that you can track the errors when you're doing AJAX interaction.
I think the problem is in the following code:
$aux->setCatDate($row[0]);
$aux->setCatName($row[1]);
$aux->setCatKey($row[2]);
Try to use the column name to get the $row data from DB, like:
$aux->setCatDate($row['addedat']);
$aux->setCatName($row['catname']);
$aux->setCatKey($row['catkey']);
and then see the result.
I have a XML document:
<product>
<item>
<item00>
<name>DVD</name>
</item00>
</item>
</product>
<product>
<item>
<item11>
<name>CD</name>
</item11>
</item>
</product>
And I would like to show the names of these products, but there are products with item as "item00" and "item11".
I tried adding the path regular expressions in XPath, but without success.
There is a possibility I display the name of these products (DVD and CD) using XPath?
<?php
$xml = 'file.xml';
$content = '';
$f = fopen($xml, 'r');
while($data = fread($f, filesize($xml))) {
$content.= $data;
}
fclose($f);
preg_match_all('/\<product\>(.*?)\<\/product\>/s', $content, $product);
$product = $product[1];
$doc = new SimpleXMLElement($content);
for($i = 0; $i <= count($product) - 1; $i++) {
// So far, no problems. Seriously.
// The issue starts here.
$query = $doc->xpath('/product/item/???');
foreach($query as $item) {
echo $item->name . '<br>';
}
}
?>
Where "???" is the problem with "item00" and "item11".
If anyone knows and can help me, I'll be very grateful!
Here is the total working code
<?php
$xml = 'file.xml';
$content = '';
$f = fopen($xml, 'r');
while($data = fread($f, filesize($xml))) {
$content.= $data;
}
fclose($f);
$content = "<root>$conten</root>";
$doc = new SimpleXmlElement($content);
$query = $doc->xpath('//item/child::*');
foreach($query as $item) {
echo $item->name . '<br>';
}
i dont think you can use regex in that context, that's the very reason to use attributes
<item num="00">
however check this, i believe it is what you are looking for
those 00 11 things really should be attributes
im trying to create a xml file using php.everytime i run the code the page displayes the code from a certain point as text on the screen.the code i hav is as follows:
<?php
if(!$dbconnet = mysql_connect('I took out the details')){
echo "connection failed to the host.";
exit;
}
if (!mysql_select_db('siamsati_db')){
echo "Cannot connect to the database.";
exit;
}
$table_id = 'events';
$query = "SELECT * FROM $table_id";
$dbresult = mysql_query($query, $dbconnect);
$doc = new DomDocument('1.0');
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
while($row = mysql_fetch_assoc($dbresult)){
$ooc = $doc->createElement($table_id);
$occ = $root->appendChild($occ);
foreach ( $row as $fieldname => $fieldvalue){
$child = $doc->createElement($fieldname);
$child = $occ->appendchild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}
}
$xml_string = $doc->saveXML();
echo $xml_string;
?>
and the page when displayed shows:
createElement('root'); $root =
$doc->appendChild($root); while($row =
mysql_fetch_assoc($dbresult)){ $ooc =
$doc->createElement($table_id); $occ =
$root->appendChild($occ); foreach (
$row as $fieldname => $fieldvalue){
$child =
$doc->createElement($fieldname);
$child = $occ->appendchild($child);
$value =
$doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} } $xml_string = $doc->saveXML();
echo $xml_string; ?>
is there something ive missed.ive checked all the quotes thinking it was that at first but they all seem to be right.any suggestions on what im doing wrong are much appreciated?
Set the content type to be XML, so that the browser will recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );
In your code Change it to:
// Set the content type to be XML, so that the browser will recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );
// "Create" the document.
$doc = new DOMDocument( "1.0", "ISO-8859-15" );
+++I think you can do something like this
<root>
<?
foreach ( $row as $fieldname => $fieldvalue){
?>
<events>
<fieldname><?=fieldname; ?></fieldname>
<fieldvalue><?=$fieldvalue; ?></fieldvalue>
</events>
}
?>
</root>
In the code you've posted here the initial <?php tag is missing...