Send xml file in textarea form in PHP - php

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; ?>

Related

PHP Simple HTML Dom parser returns 0

I use PHP Simple HTML Dom parser to get some elements of a page. Unfortunately, I get as a result 0 or 1... I would like to get the innerHTML instead.
Here is a photo of the dom:
And here is my code:
include('simple_html_dom.php');
// We take the url we want to scrape
$URL = 'https://www.legifrance.gouv.fr/affichTexte.do?cidTexte=JORFTEXT000033011065&dateTexte=20160821';
// Curl init
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close($ch);
// We get the html
$html = new simple_html_dom();
$html->load($result);
// Find all article blocks
foreach($html->find('div.data') as $article) {
$item['title'] = $article->find('.titreSection', 0) ->plaintext;
$resultat[] = "<p>" + $item['title']."</p></br>";
}
include 'vue_scrap.php';
?>
Here is the code of my view:
foreach ($resultat as $result){
echo $result;
}
Thank you for your help.
In fact I just did a mistake with that line:
$resultat[] = "<p>" + $item['title']."</p></br>";
The correct version is:
$resultat[] = "<p>".$item['title']."</p></br>";

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).

PHP curl Inside Foreach

EDIT:What is really happening is that a new xml is created each time but it is adding the new $html information to the previous so by the time it gets to the last element in the list being curled, it is saving parsed information from all previous curls. Can't figure out what is wrong.
Having trouble with a curl not executing as expected. In the code below I have a foreach loop that loops thru a list ($textarray) and passes the list element to a curl and also used to create an xml file using the element as the file name. The curl then returns $html which is then parsed and saved to an xml. The script runs, the list is passed, the url is created and passed to the curl function. I get an echo showing the correct url, a return is made and then each return is parsed and saved to the appropriate file. The problem seems to be that the curl is not actually curling the new $url. I get the exact same information saved in every xml file. I no this is not correct. Not sure why this is happening. Any help appreciated.
Function FeedXml($textarray){
$doc=new DOMDocument('1.0', 'UTF-8');
$feed=$doc->createElement("feed");
Foreach ($textarray as $text){
$url="http://xxx/xxx/".$text;
echo "PATH TO CURL".$url."<br>";
$html=curlurl($url);
$xmlsave="http://xxxx/xxx/".$text;
$dom = new DOMDocument(); //NEW dom FOR EACH SHOW
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$dom->formatOutput = true;
$dom->preserveWhiteSpace = true;
//PARSE EACH RETURN INFORMATION
$images= $dom->getElementsByTagName('img');
foreach($images as $img){
$icon= $img ->getAttribute('src');
if( preg_match('/\.(jpg|jpeg|gif)(?:[\?\#].*)?$/i', $icon) ) {
// ITEM TAG
$item= $doc->createElement("item");
$sdAttribute = $doc->createAttribute("sdImage");
$sdAttribute->value = $icon;
$item->appendChild($sdAttribute);
} // IMAGAGE FOR EACH
$feed->appendChild($item);
$doc->appendChild($feed);
$doc->save($xmlsave);
}
}
}
Function curlurl($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);//0-FALSE 1 TRUE
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER ,FALSE);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT,'10');
$html = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $httpcode;
return $html;
}
Thanks for pointing out my shortcomings on the above. I have figured out the problem. The following needed to be moved into the Foreach.
$doc=new DOMDocument('1.0', 'UTF-8');
$feed=$doc->createElement("feed");

Parsing through XML with namespace

I try to parse through a XML file with a difficult namespace but this does not work.
Hope you can help me with this issue.
This is my XML file which is generated from an URL:
<searchresultresponse xmlns="urn:veloconnect:catalog-1.1" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-1.0" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-1.0" xmlns:vct="urn:veloconnect:transaction-1.0" xmlns:vco="urn:veloconnect:order-1.1" xmlns:vcc="urn:veloconnect:catalog-1.1">
<vct:buyersid>417641</vct:buyersid>
<vct:responsecode>200</vct:responsecode>
<vct:transactionid>dmVsb2Nvbm5lY3Rfc2VhcmNoLkhJUl9TUkNfMTIwMg</vct:transactionid>
<vct:statuscode>2</vct:statuscode>
<startindex>0</startindex>
<count>500</count>
<totalcount>51691</totalcount>
<resultformat>ITEM_TYPE</resultformat>
<cac:item>
<cbc:description>BREMSBELAG GALFER ORGAN. FD171-G1054 (KBA)</cbc:description>
<cac:sellersitemidentification>
<cac:id>04303400</cac:id>
</cac:sellersitemidentification>
<cac:standarditemidentification>
<cac:id identificationschemeid="EAN/UCC-13">8400160001718</cac:id>
</cac:standarditemidentification>
<cac:manufacturersitemidentification>
<cac:id>FD171-G1054</cac:id>
<cac:issuerparty>
<cac:partyname>
<cbc:name>Galfer</cbc:name>
</cac:partyname>
</cac:issuerparty>
</cac:manufacturersitemidentification>
<cac:baseprice>
<cbc:priceamount amountcurrencyid="EUR">5.95</cbc:priceamount>
<cbc:basequantity quantityunitcode="EA">1</cbc:basequantity>
</cac:baseprice>
<cac:recommendedretailprice>
<cbc:priceamount amountcurrencyid="EUR">10.9</cbc:priceamount>
<cbc:basequantity quantityunitcode="EA">1</cbc:basequantity>
</cac:recommendedretailprice>
</cac:item>
I grab this from an URL via PHP like this:
<?php
error_reporting(E_ALL);
$url = "http://somedomain.com/feed";
set_time_limit(0);
$ch = curl_init($url);// or any url you can pass which gives you the xml file
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$xml = curl_exec($ch);
curl_close($ch);
$namespaces = $xml->getNameSpaces(true);
$cac = $xml->children($namespaces['cac']);
foreach ($xml as $entry){
$cac = $xml->children($namespaces['cac']);
echo $cac->item;
}
?>
I always all data shown without linebreaks etc. but I need to fetch specific objects to save them in array (later).
This namesapce here is really wired.

How can I read all the <status> tags from the Twitter timeline for a user?

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.

Categories