How to send and receive a xml to another computer - php

I have two computers, comp 1 as branch 1 and comp 2 as main branch. in comp 1 i have generated an xml of my database query using php.
`<?php
header ("Content-Type:text/xml");
//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "root";
$config['mysql_pass'] = "donnaluz";
$config['db_name'] = "global89_branch1";
$config['table_name'] = "branchsales";
//connect to host
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
//select database
#mysql_select_db($config['db_name']) or die( "Unable to select database");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name'];
$xml = "<$root_element>";
/*$title = $doc->createElement("branchsales");
$title = $root->appendChild($title);
$text = $doc->createTextNode("sales");
$text = $title->appendChild($text);
*/
//select all items in table
$sql = "SELECT branch.branchname,branchadmin.username,branchcomp.*,branchsales.*,days.day
FROM branchsales,branch,branchadmin,branchcomp,days
WHERE
branchsales.comp_id = branchcomp.comp_id
AND branchsales.admin_id = branchadmin.admin_id
AND branchsales.branch_id = branch.branch_id
AND branchsales.day_id = days.day_id";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<".$config['table_name'].">";
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//$key holds the table column name
$xml .= "<$key>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "<![CDATA[$value]]>";
//and close the element
$xml .= "</$key>";
}
$xml.="</".$config['table_name'].">";
}
//close the root element
$xml .= "</$root_element>";
//send the xml header to the browser
header ("Content-Type:text/xml");
echo $xml;
?>
` which looks like this
<branchsales>
<branchname>Branch1</branchname>
<username>garfield</username>
<comp_id>1</comp_id>
<admin_id>1</admin_id>
<pcnum>1</pcnum>
<starttime>09:00:00</starttime>
<endtime>10:00:00</endtime>
<totaltime>1:00:00</totaltime>
<compcharge>10.00</compcharge>
<id>1</id>
<branch_id>1</branch_id>
<day_id>5</day_id>
<timeopened>8:00:00</timeopened>
<timeclosed>23:00:00<timeclosed>
blah blah.. so on..
The thing is, I want that generated xml to be sent out to comp 2,
looking like this in a table
|ID|Day |Watcher |Branch | Current Date | Time Opened | Time closed | PC No. | so on...
1 Friday garfield Branch1 29-03-13 8:00:00 23:00:00 1
THIS IS MY SEND CODE, BUT ITS NOT WORKING
<?
php
$file = 'http://localhost/thesis/xmldailyrep.php';
$xml_builder = 'simplexml_load_file($file)';
$ch = curl_init("http://172.16.0.55/dailyrep1.php");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:text/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, "http://localhost/thesis/xmldailyrep.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ch_result = curl_exec($ch);
curl_close($ch);
echo $ch_result;
?>
MY RECEIVE CODE IN COMP 2 is this
<?php
/*
* XML Server.
*/
// We use php://input to get the raw $_POST results.
$xml_post = file_get_contents('xmldailyrep.php');
// If we receive data, save it.
if ($xml_post) {
$xml_file = 'received_xml_' . date('Y_m_d-H-i-s') . '.xml';
$fh = fopen($xml_file, 'w') or die();
fwrite($fh, $xml_post);
fclose($fh);
// Return, as we don't want to cause a loop by processing the code below.
return;
}
?>
PLEASE HELP

As far as I know, from the title. I will use frameworks to do this work. Like Apache Camel, Mule ESB. If its going to be a large scale implementation.
If you can tell us the whole story, it could be easier to help you.
-Guru
#gnanagurus

$file = 'http://localhost/thesis/xmldailyrep.php';
$xml_builder = file_get_contents($file);

Related

Integrating PHP Curl

I have the code below which calls up an MySQLi and presents it in XML form in my browser.
The next stage is that instead of presenting it in my browser I want to send it to another IP address using PHP Curl. Please can someone help me with the extra code needed to do that.
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}
$sql = "SELECT SessionLogs.sessionid, SessionLogs.eventid, BetStatus.BetStatus, EventStatus.EventStatus, SessionLogs.activestatusid
FROM SessionLogs INNER JOIN
EventStatus ON SessionLogs.eventstatusid = EventStatus.EventStatusID INNER JOIN
BetStatus ON SessionLogs.betstatusid = BetStatus.BetStatusID
where ActiveStatusID = 1
";
$res = $mysqli_connection->query($sql);
$xml = new XMLWriter();
$xml->openURI("php://output");
$xml->startDocument();
$xml->setIndent(true);
$xml->startElement('Alive');
$xml->writeAttribute('timestamp', date('c'));
if($res === FALSE) {
die(mysqli_error()); // TODO: better error handling
}
while ($row = mysqli_fetch_assoc($res)) {
$xml->startElement("Event");
$xml->writeAttribute('sessionid', $row['sessionid']);
$xml->writeAttribute('eventid', $row['eventid']);
$xml->writeAttribute('BetStatus', $row['BetStatus']);
$xml->writeAttribute('EventStatus', $row['EventStatus']);
$xml->writeAttribute('activestatusid', $row['activestatusid']);
$xml->endElement();
}
$xml->endElement();
$xml->endElement();
header('Content-type: text/xml');
$xml->flush();
?>
Please help. Thanks.
You can send xml data using curl with following code
$input_xml = ''; //XML Data
$url=''; // URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
Use $xml->openMemory(); and $xmlString = $xml->outputMemory() to catch the cache of your XMLWriter-Object (Documentation).

Import XML into MySQL database

I'm new to coding, trying to create a database from an XML file which is a list of industries, company names and symbols. I've seen a few examples of a PHP code that imports the data into MySQL which looked something like:
<?php
$url ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.industry%20where%20id%20in%20(select%20industry.id%20from%20yahoo.finance.sectors)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); //getting url contents
$data = curl_exec ($ch); //execule curl request
curl_close($ch);
$xml = simplexml_load_string($data);
$con=mysql_connect("localhost", "root", ""); //connect to server
mysql_select_db("symbol_list", $con) or die(mysql_error()); //select database
foreach ($xml -> item as $row) {
$industry = $row -> industry;
$company = $row -> name;
$symbol = $row -> symbol;
// perform sql query
$sql = "INSERT INTO 'symbols_xml' ('industry', 'company', 'symbol')"
. "VALUES ('$industry', '$company', '$symbol')";
$result = mysql_query($sql);
if (!$result) {
echo 'MySQL ERROR';
} else {
echo 'SUCCESS';
}
}
?>
However, because the XML is formatted like this:
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="215" yahoo:created="2015-03-02T20:58:57Z" yahoo:lang="en-US">
<results>
<industry id="112" name="Agricultural Chemicals">
<company name="Adarsh Plant Protect Ltd" symbol="ADARSHPL.BO"/>
<company name="African Potash Ltd" symbol="AFPO.L"/>
......
</industry>
<industry id="132" name="Aluminum">
<company name="AEI Corp Ltd" symbol="A18.SI"/>
<company name="Alcoa Inc" symbol="AA.BA"/>
<company name="Alcoa Inc" symbol="AA.MX"/>
......
My PHP code above is unable to recognise the values...
Is there any way to import the attributes (industry name, company name and symbol) so that it looks something like:
#| Industry | Company | Symbol
-|----------- ------------ -------
1| Aluminium | Alcoa Inc. | AA.BA
and so on..
I just recently started learning PHP and databases so please forgive me if this is a noobish question that wasted your time. xD
Thanks.
You were actually not very far.
In order to fetch an attribute, you can do it in two ways :
Access it as if the node was an array $node['attributeName']
Use a method named attributes(), and you could also do : $node->attributes()->attributeName;
Here is your code updated :
<?php
$url ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.industry%20where%20id%20in%20(select%20industry.id%20from%20yahoo.finance.sectors)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); //getting url contents
$data = curl_exec ($ch); //execule curl request
curl_close($ch);
$xml = simplexml_load_string($data);
$con=mysql_connect("localhost", "root", ""); //connect to server
mysql_select_db("symbol_list", $con) or die(mysql_error()); //select database
foreach ($xml->results->industry as $industryNode)
{
foreach ($industryNode->company as $companyNode)
{
$industry = (string) $industryNode['name'];
$company = (string) $companyNode['name'];
$symbol = (string) $companyNode['symbol'];
// perform sql query
$sql = "INSERT INTO 'symbols_xml' ('industry', 'company', 'symbol')"
. "VALUES ('$industry', '$company', '$symbol')";
$result = mysql_query($sql);
if (!$result)
{
echo 'MySQL ERROR';
}
else
{
echo 'SUCCESS';
}
}
}

Database information into Facebook Page Tab? XML and cURL

I am trying to create a simple Facebook Page Tab that retrieves current information from my database. I quickly learned that cross-site scripting won't work, as a working demo on the actual website worked great, but produced no results on heroku.
Here is what I have in heroku now. How do I make curl process the page before it returns a result?
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://www.url.com/output.html');
$result = curl_exec ($curl);
curl_close ($curl);
print $result;
?>
Here is the page that creates the formatted XML that is located on my webserver:
<?php
require_once('connectDB.php');
$xslt_file = "xmlstyle.xsl";
mysql_select_db($database_DB, $db);
$query = sprintf("SELECT * from db");
$result = mysql_query($query, $db) or die(mysql_error());
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
if ($xslt_file) $XML .= "<?xml-stylesheet href=\"$xslt_file\" type=\"text/xsl\" ?>";
// root node
$XML .= "<result>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t<row>\n";
$i = 0;
// cells
foreach ($row as $cell) {
// Escaping illegal characters - not tested actually ;)
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = mysql_field_name($result,$i);
// creates the "<tag>contents</tag>" representing the column
$XML .= "\t\t<" . $col_name . ">" . $cell . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t</row>\n";
}
$XML .= "</result>\n";
// output the whole XML string
echo $XML;
?>
I'm sure I'm over complicating this whole thing, but it has been somewhat enjoyable to try to make it work. If there is a much easier way to get the same result, I'm all ears. Thanks in advance.
Use the RETURNTRANSFER option:
//Set curl to return the page instead of sending it to the browser
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
References
curl manpage
PHP curl binding

Inserting Query String Variables in XML using PHP/curl

I'm trying to send some information to our CRM from a form on our site and am getting stuck on inserting the variables into the XML. Here is a simplified version of my code. Notice where I'm trying to insert the $email variable within the XML variable...which is not working.
<?php
$email = $_GET["email"];
$xml = '<xmlrequest>
<details>
<emailaddress>$email</emailaddress>
<mailinglist>8</mailinglist>
<format>html</format>
<confirmed>no</confirmed>
</details>
</xmlrequest>
';
$ch = curl_init('http://mysite.com/xml.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$result = #curl_exec($ch);
if ($result === false) {
echo "Error performing request";
} else {
$xml_doc = simplexml_load_string($result);
header( "Location: http://mysite.com/confirmation?email=$email" ) ;
//echo 'Status is ', $xml_doc -> status, '<br/>';
if ($xml_doc -> status == 'SUCCESS') {
echo 'Data is ', $xml_doc -> data, '<br/>';
} else {
echo 'Error is ', $xml_doc -> errormessage, '<br/>';
}
}
?>
If I just type in an email address value for the API works fine. However, I'm clueless on how to pull this in dynamically from a PHP variable. Any help is greatly appreciated!
The string definition is bad
use this
$xml = "<xmlrequest>
<details>
<emailaddress>{$email}</emailaddress>
<mailinglist>8</mailinglist>
<format>html</format>
<confirmed>no</confirmed>
</details>
</xmlrequest>";
or this
$xml = '<xmlrequest>
<details>
<emailaddress>' . $email . '</emailaddress>
<mailinglist>8</mailinglist>
<format>html</format>
<confirmed>no</confirmed>
</details>
</xmlrequest>';
Because this variable probably can be various string I think it's better if you use <![CDATA[]]> section around the email.

The HTTP method received is not valid. Only POST is accepted

OK, I have this php file for my HSBC bank processing using the API, I have this working fine on 2 of my other websites, however the SAME file is failing on the other two sites, I have no idea why. My web developer is stumped and decided to create a test file, Here is the code from the test file:
<?php
echo "payment processing...";
$amount = 100;// round($_POST["realamount"], 2) * 100;
$fullName = "test";//$_POST['name'];
$Address1 = "test";//$_POST['address1'];
$Address2 = "test";//$_POST['address2'];
$city ="test";// $_POST['city'];
$county = $city;
$postcode = "test";//$_POST['zipcode'];
$country = "GRB";//$_POST['country'];
$phone = "test";//$_POST['telephone'];
$email = "a#a.com";//$_POST['emailaddress'];
$cardNumber = "337877666233434";//$_POST['cardNumber'];
$cardExp = "03/2011";//$_POST['ccmonth'] . "/" . substr($_POST["ccyear"],2,2);
$cvdIndicator = "111";//$_POST['cvdIndicator'];
$cvdValue = "111";//$_POST['cvdValue'];
$issueNumber = "111";//$_POST['issueNumber'];
$cardType = "VI";//$_POST['cardType'];
$testRead = "<?xml version='1.0' encoding='UTF-8'?>
<EngineDocList>
<DocVersion>1.0</DocVersion>
<EngineDoc>
<ContentType>OrderFormDoc</ContentType>
<User>
<Name>xxx</Name>
<Password>xxx</Password>
<ClientId>xxx</ClientId>
</User>
<Instructions>
<Pipeline>PaymentNoFraud</Pipeline>
</Instructions>
<OrderFormDoc>
<Mode>P</Mode>
<Comments/>
<Consumer>
<Email/>
<PaymentMech>
<CreditCard>
<Number>".$cardNumber."</Number>
<Expires DataType='ExpirationDate' Locale='840'>".$cardExp."</Expires>
<Cvv2Val>".$cvdValue."</Cvv2Val>
<Cvv2Indicator>".$cvdIndicator."</Cvv2Indicator>
<IssueNum>".$issueNumber."</IssueNum>
</CreditCard>
</PaymentMech>
</Consumer>
<Transaction>
<Type>Auth</Type>
<CurrentTotals>
<Totals>
<Total DataType='Money' Currency='826'>".$amount."</Total>
</Totals>
</CurrentTotals>
</Transaction>
</OrderFormDoc>
</EngineDoc>
</EngineDocList>";
?>
<?php
//$url = "https://www.uat.apixml.netq.hsbc.com";
$url = "https://www.secure-epayments.apixml.hsbc.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$testRead);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$result_tmp = curl_exec ($ch);
curl_close ($ch);
///////////////////////////////////////
// use XML Parser result
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($xml_parser, $result_tmp, $vals, $index);
xml_parser_free($xml_parser);
//print_r($vals); // print all the arrays.
//print_r($vals[29]); // print only the selected array.
$val1 = $vals[21];
// ProcReturnMsg
$paymentResult = $val1[value];
$result_tmp = "";
$k=0;
$findthis = false;
$findthis2 = false;
foreach ($vals as $val) {
$result_tmp.= $k."{";
foreach($val as $d => $a) {
$result_tmp.="[".$d."]".$a;
if($d=="tag" && $a=="TransactionStatus"){
$findthis = true;
}
if($d=="value" && $findthis){
$tResult = $a;
$findthis = false;
}
if($d=="tag" && $a=="Text"){
$findthis2 = true;
}
if($d=="value" && $findthis2){
$tResult2 = $a;
$findthis2 = false;
}
}
$result_tmp.= "}";
$k++;
}
echo $tResult2.$tResult;
?>
Here is an example of one of the sites not working gs.net
The output is:
payment processing... The HTTP method received is not valid. Only POST is accepted.
Whereas when I upload this exact same file to some of my other web hosts such as:
HGL working example
The output here is payment processing... Unable to determine card type. ('length' is '15')E
This sounds like an error message, but basically that error is not important, so the latter is what we are trying to achieve in the first link.
I have even uploaded this file to some really basic hosting accounts of mine, sometimes it will work sometimes it won't, so I'm guessing it's something to do with what the hosting company are allowing or have switched On/Off.
Any ideas please?
Thank you
This seems to have been caused by a PHP upgrade applied to the server and it was driving me crazy.
The solution is to set the following SSL options when specifying the CURL connection.
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'RC4-MD5');
check if curl is enabled on those servers that don't work for starters. use phiinfo() function to check.

Categories