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).
Related
I am attempting to access an XML feed (with username and password) by using XMLReader.
Formerly, I had integrated the credentials into the url (e.g. http://username:password#mysite.com); however, this is not working now.
I get 'XPath query failed for bio' at the final check in my code.
Would it be possible to specify the username/password in XMLReader?
Thanks for any leads.
My code (edited to include my Curl code):
<?php
$secondary_user_id = "jsmith";
$url_bio = "http://username:password#mysite.com";
//
$a_username='username';
$a_password='password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_bio);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $a_username . ':' . $a_password);
$result = curl_exec($ch);
$a_error = curl_error($ch);
echo '<br>'.$a_error.'<br>';
curl_close($ch);
//
$reader = new XMLReader();
//$reader->open($url_bio);
$reader->XML($result);
while ($reader->read())
{
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Users')
{
//the code works to this point
echo 'success<br>';
$node = $reader->expand();
$doc = new DOMDocument('1.0','UTF-8');//
$n = $doc->importNode($node,true);
$doc->appendChild($n);
//$xml_bio_report = simplexml_import_dom($doc->importNode($reader->expand(),true));//
$xml_bio_report = simplexml_import_dom($n);//
$xml_bio_report->registerXPathNamespace('xlink','http://www.w3.org/1999/xlink');
$xml_bio_report->registerXPathNamespace('dmu','http://www.digitalmeasures.com/schema/user-metadata');
//echo $xml_bio_report->Users->User;
$xml_bio_report_abbrev = $xml_bio_report->xpath('//User[#SecondaryID="'.$secondary_user_id.'"]');
if ($xml_bio_report_abbrev){
echo '<h1>'.$xml_bio_report_abbrev[0]['username'].'</h1>';
echo '<h1>'.$xml_bio_report_abbrev[0]['SecondaryID'].'</h1>';
} else {
echo 'XPath query failed for bio';
}
}
}
?>
XMLReader::open() uses the PHP streamwrapper. Here is a function called libxml_set_streams_context() that allows to set the context for the next open/load call.
$opts = array(
'http' => array(
'user_agent' => 'PHP libxml agent',
)
);
$context = stream_context_create($opts);
libxml_set_streams_context($context);
$reader = new XMLReader();
$reader->open($url_bio);
//...
I am trying to create a script that extracts text from a website table and displays it via php. When I run it on this address :
http://lmvz.anofm.ro:8080/lmv/detalii.jsp?UNIQUEJVID=50/01/1150001435/1&judet=50
It turns out empty. Is there something wrong with the code? And how can I fix / improve it?
<?php
include_once('simple_html_dom.php');
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
// Start a cURL resource
$ch = curl_init();
// Set options for the cURL
curl_setopt($ch, CURLOPT_URL, 'http://lmvz.anofm.ro:8080/lmv/detalii.jsp?UNIQUEJVID=50/01/1150001435/1&judet=50'); // target
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // provide a user-agent
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow any redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the result
// Execute the cURL fetch
$result = curl_exec($ch);
// Close the resource
curl_close($ch);
// Output the results
echo $result;
function scraping() {
// create HTML DOM
$html = file_get_html('http://lmvz.anofm.ro:8080/lmv/detalii.jsp?UNIQUEJVID=50/01/1150001435/1&judet=50');
// get article block
if($html && is_object($html) && isset($html->nodes)){
foreach($html->find('/html/body/table') as $article) {
// get title
$item['titlu'] = trim($article->find('/html/body/table/tbody/tr[1]/td/div', 0)->plaintext);
// get body
$item['tr2'] = trim($article->find('/html/body/table/tbody/tr[2]', 0)->plaintext);
$item['tr3'] = trim($article->find('/html/body/table/tbody/tr[3]', 0)->plaintext);
$item['tr4'] = trim($article->find('/html/body/table/tbody/tr[4]', 0)->plaintext);
$item['tr5'] = trim($article->find('/html/body/table/tbody/tr[5]', 0)->plaintext);
$item['tr6'] = trim($article->find('/html/body/table/tbody/tr[6]', 0)->plaintext);
$item['tr7'] = trim($article->find('/html/body/table/tbody/tr[7]', 0)->plaintext);
$item['tr8'] = trim($article->find('/html/body/table/tbody/tr[8]', 0)->plaintext);
$item['tr9'] = trim($article->find('/html/body/table/tbody/tr[9]', 0)->plaintext);
$item['tr10'] = trim($article->find('/html/body/table/tbody/tr[10]', 0)->plaintext);
$item['tr11'] = trim($article->find('/html/body/table/tbody/tr[11]', 0)->plaintext);
$item['tr12'] = trim($article->find('/html/body/table/tbody/tr[12]', 0)->plaintext);
$ret[] = $item;
}
// clean up memory
$html->clear();
unset($html);
return $ret;}
}
// -----------------------------------------------------------------------------
// test it!
$ret = scraping();
foreach($ret as $v) {
echo $v['titlu'].'<br>';
echo '<ul>';
echo '<li>'.$v['tr2'].'</li>';
echo '<li>'.$v['tr3'].'</li>';
echo '<li>'.$v['tr4'].'</li>';
echo '<li>'.$v['tr5'].'</li>';
echo '<li>'.$v['tr6'].'</li>';
echo '<li>'.$v['tr7'].'</li>';
echo '<li>'.$v['tr8'].'</li>';
echo '<li>'.$v['tr9'].'</li>';
echo '<li>'.$v['tr10'].'</li>';
echo '<li>'.$v['tr11'].'</li>';
echo '<li>'.$v['tr12'].'</li>';
echo '</ul>';
}
?>
Because in foreach you use result of finding /html/body/table you should not use full path but ask:
$item['titlu'] = trim($article->find('/tbody/tr[1]/td/div', 0)->plaintext);
$item['tr2'] = trim($article->find('/tbody/tr[2]', 0)->plaintext);
and so on...
To your curl works, you need move
$ch = curl_init();
before first curl_setopt
I need to send content of my xml file located on server to text form.
I try to use curl method in PHP, but i don't know how to read content from xml file and save it to variable. What's wrong?
Here PHP-code:
if ($model->getSOrderStatuses()->id == 1) {
$xml = new XMLWriter();
$xml->openMemory();
$xml->openURI('uploads/files/orders.xml');
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement("order"); //start root
$xml->writeElement("id", $model->getId());
$xml->writeElement("date", gmdate("Y-m-d\/H:i:s", $model->getDateCreated()));
$xml->writeElement("customer", $model->getUserFullName());
$xml->writeElement("phone", $model->getUserPhone());
$xml->writeElement("email", $model->getUserEmail());
$xml->writeElement("delivery_type", $model->getSDeliveryMethods()->getId());
$xml->writeElement("delivery_adress", $model->getUserDeliverTo());
$xml->writeElement("payment_type", $model->getSPaymentMethods()->getId());
$xml->writeElement("comment", $model->getUserComment());
$xml->startElement("products"); //open element
foreach ($model->getSOrderProductss() as $sOrderProduct) {
$total = $total + $sOrderProduct->getQuantity() * $sOrderProduct->toCurrency();
$product = $sOrderProduct->getSProducts();
$xml->startElement("row"); //open element
$xml->writeAttribute("code", $product->getUrl());
$xml->writeAttribute("qty", $sOrderProduct->getQuantity());
$xml->writeAttribute("price", $sOrderProduct->toCurrency());
$xml->writeAttribute("sum", $sOrderProduct->getQuantity() * $sOrderProduct- >toCurrency());
$xml->endElement(); //close element
}
$xml->endElement(); //close element
$xml->writeElement("sum", my_money_format('',$total));
$xml->endElement(); //close root
$xml->flush();
$xmlorder = 'uploads/files/orders.xml';
$ch = curl_init('http://pathtomyserver/?action=newor');
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlorder);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
echo($xmlorder);
$info=curl_getinfo($ch);
curl_close($ch);
}
}
form:
>>link
You could use this
$xml = file_get_contents("path/to/xml.xml");
Then simply output to textarea
<textarea name="xml"><?php echo $xml; ?>
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);
I am trying to read twitter timeline with cURL, and for some reason I am unable to use preg_match. Here's my current code, do you see any issues?
$feed = "http://twitter.com/statuses/user_timeline/antonpug.xml?count=3";
function parse_feed($feed) {
//$matches = Array();
preg_match_all("/<status>(.*?)<\/status>/", $content[0], $matches);
return $matches[0];
//$stepOne = explode("<content type=\"html\">", $feed);
//$stepTwo = explode("</content>", $stepOne[1]);
//$tweet = $stepTwo[0];
//$tweet = htmlspecialchars_decode($tweet,ENT_QUOTES);
//return $tweet;
}
//Initialize the Curl session
$ch = curl_init();
//Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $feed);
//Execute the fetch
$twitterFeed = curl_exec($ch);
//Close the connection
curl_close($ch);
//$twitterFeed = file_get_contents($feed);
echo(parse_feed($twitterFeed));
I guess the better idea would be to use simplexml to work with XML as with object.
Your function then would be something like
function parse_feed($feed) {
$xml = simplexml_load_string($feed);
if(isset($xml->status)) {
return $xml->xpath('status');
} else {
return false;
}
}
It will return simplexml object.