Read URL Content in javascript using php - php

I want to read the content of a URL in javascript. The URL is not on my domain so I need a middle layer that can access cross domain.
I tried to use a PHP function to read the URL and return the result to javascript using jquery but it didn't work.
Here is my trial:
I created a php file named "phpjs_test.php"
<?php
function get_data(){
$url='http://asmary.dreameg.com/texttable.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
$content = htmlspecialchars($content);
curl_close($ch);
$content = nl2br($content);
return $content;
}
?>
and this is the javascript code:
<script>
$(document).ready(function () {
//httpQuery("http://asmary.dreameg.com/texttable.txt");
getOutput();
});
function getRequest() {
var req = false;
try {
// most browsers
req = new XMLHttpRequest();
} catch (e) {
// IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
return req;
}
function getOutput() {
var ajax = getRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
document.getElementById('output').innerHTML = ajax.responseText;
}
};
ajax.open("GET", "phpjs_test.php", true);
ajax.send(null);
}
I'm completely new to PHP so I don't know even the PHP function is correct or not.

You should just use jQuery ajax methods instead of creating XMLHTTPRequest you don't have to bother with adding more code for IE plus you're already loading the jQuery library. Also if you set the header to Allow-Origin-Access in your PHP file and specify the other domain you're requesting from then you can make an AJAX request and get the response otherwise it will return nothing or in your dev tools network tab it will show a 403 - Forbidden.
Access-Control-Allow-Origin syntax

Change the PHP file to:
<?php
$url='http://asmary.dreameg.com/texttable.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
$content = explode('~',$content);
foreach($content as $c)
{
$records[] = explode('|',$c);
}
$content = json_encode($records);
echo $content;
?>
Javascript will receive a json array like this
[["1","name1","10","city1"],["2","name2","20","city2"],["3","name3","30","city3"],["4","name4","40","city4"],["5","name5","50","city5"],["6","name6","60","city6"],["7","name7","7","city7"],["8","name8","80","city8"],["9","name9","90","city9"],["10","name10","100","city10"],["11","name11","11","city11"],["12","name12","12","city12"],["13","name13","13","city13"],["14","name14","14","city14"],["15","name15","15","city15"],["16","name16","16","city16"],["17","name17","17","city17"],["18","name18","18","city18"],["19","name19","19","city19"],["20","name20","20","city20"],[""]]

Related

How to disable output buffering for Laravel

I have this function in controller ImportController.php, I seding a file to import using the Laravel Excel library...
Laravel version: 5.5
Php Version: PHP 7.2.19-0ubuntu0.18.10.1 (cli) (built: Jun 4 2019 14:46:43) ( NTS )
One sheet the client is sending is taking a lot of time. Then I make a progress bar for the client get a feedback when is importing/saving data from the sheet.
This is the javascript function here is sending the sheet and token and if is a ajax request.
.....
let fd = new FormData();
fd.append(_archiveInputId, archivoSeleccionado.files[0]);
fd.append("_token", window.Laravel.csrfToken);
fd.append("isHttpRequest", true);
let xmlHTTP = new XMLHttpRequest();
xmlHTTP.upload.addEventListener("progress", progressFunction, false);
xmlHTTP.addEventListener("load", transferCompleteFunction, false);
xmlHTTP.addEventListener("error", uploadFailed, false);
xmlHTTP.addEventListener("abort", uploadCanceled, false);
xmlHTTP.responseType = 'json';
xmlHTTP.response = 'json';
xmlHTTP.open("POST", _url, true);
xmlHTTP.send(fd);
.....
/**
* Progress Function
* #param evt
*/
function progressFunction(evt) {
console.log(evt);
}
This is my controller:
public function import(ImportFormRequest $request)
{
$isHttpRequest = $request->has('isHttpRequest') ? $request->has('isHttpRequest') : false;
if($isHttpRequest){
echo "creating EventsImport class";
flush();
sleep(1);
}
$import = new EventsImport(EventsImport::TYPE_SIMPLE, $request->file('sheet'));
try{
if($isHttpRequest){
echo "importing data from sheet";
flush();
sleep(1);
}
Excel::import($import, $request->file('sheet'));
}catch (\Exception $e){
return $this->returnJsonResponseHttpRequest("nok","Erro ao realizar importação! Erro: ".$e->getMessage());
}
}
These outputs echo "importing data from sheet" is for testing.
I tried with:
ob_flush();
flush();
php.ini -> output_buffering=Off
.htaccess -> mod_env.c -> SetEnv no-gzip 1
But none worked (in laravel). In tests outside Laravel ob_flush and flush works fine.
Anyone have any idea?
After a long time and a travel along mountains and 5 cigarettes.
In PHP controller function add:
$response = new StreamedResponse(function() use ($request) {
for($i = 0; $i <= 3; $i++){
echo "Data: ".json_encode(['teste' => "teste"])."\n\n";
flush();
}
});
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('X-Accel-Buffering', 'no');
$response->headers->set('Cach-Control', 'no-cache');
$response->send();
sleep(5);
In javascript function to start the XMLHttpRequest:
// Remove the responseType and response as json.
let fd = new FormData();
fd.append(_archiveInputId, archivoSeleccionado.files[0]);
fd.append("_token", window.Laravel.csrfToken);
fd.append("isHttpRequest", true);
let xmlHTTP = new XMLHttpRequest();
xmlHTTP.seenBytes = 0;
xmlHTTP.onreadystatechange = function(evt) {
console.log("%c Content: ", 'color: red;', evt.srcElement.response);
};
xmlHTTP.upload.addEventListener("progress", progressFunction, false);
xmlHTTP.addEventListener("load", transferCompleteFunction, false);
xmlHTTP.addEventListener("error", uploadFailed, false);
xmlHTTP.addEventListener("abort", uploadCanceled, false);
xmlHTTP.open("POST", _url, true);
xmlHTTP.send(fd);

file_get_contents get data after 5 second from loading the web-page

i want to check if source web-page has certain word or not in PHP , but the web-page load after 5 seconds
tried classic way but didn't worked because it load the page immediately
<?php
$urlmain = "http://example.com";
$url = file_get_contents("$urlmain");
if (strpos($url, 'buy') !== false) {
$pid= 'Available';
}elseif (strpos($url, 'sold') !== false) {
$pid= 'Sold';
}else{
$pid= 'can't get data';
}
echo $pid;
?>
in previous code i want file_get_contents to get data after 5 second from loading the web-page
$url = file_get_contents("$url");
Any Idea?
If you need to load page before requesting data, you wouldn't be able to do it in 1 request.
Your best bet would be to load page normally (without any file_get_contents), wait for 5 seconds, send request via JS to a PHP script that would actually do the file_get_contents. Note that your code should end with die();, otherwise your second request will get whole page on top of your results.
Try following:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// This is your code to get data
$url = file_get_contents("$url");
if (strpos($url, 'buy') !== false) {
$pid = 'Available';
} elseif (strpos($url, 'sold') !== false) {
$pid = 'Sold';
} else {
$pid = 'can\'t get data';
}
echo $pid;
die();
}
?>
<div id="output"></div>
<script>
// On page load we start counting for 5 seconds, after which we execute function
window.onload = setTimeout(function (){
// We prepare AJAX request to the same PHP script, but via POST method
var http = new XMLHttpRequest();
var url = '';
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// When we get back successful results, we will output them to HTML node with ID = output
http.onreadystatechange = function() {
if(http.readyState === 4 && http.status === 200) {
document.getElementById('output').innerHTML = http.responseText;
}
}
http.send();
}, 5000);
</script>
You should use PHP cURL extension:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
curl_close($ch);

Google Script Error on Post

I am posting data to google sheets using php, everytime I post the data it get added on the sheet correctly, but i get the error message as
We8d#39;re sorry, a server error occurred. Please wait a bit and try
again.
My php curl post code is:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $gsurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$res = json_decode($output, 1);
My GS App Script is :
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000);
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1;
var row = [];
for (i in headers){
if (headers[i] == "Timestamp"){
row.push(new Date());
} else {
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally {
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Please help me.

How to load details automatically

Thanks guys and gals got it working
//create a function
function get_stock_data($symbol){
//set up the url to be called
$revenue_url = "http://finance.yahoo.com/q/is?s=".$symbol;
//curl call:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $revenue_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//finish by returning the result
return $result;
}
//REQUEST WILL BE POPULATED IF EITHER GET OR POST IS SET!
$data = null; // this will hold our data, declared here for accessibility
if(isset($_REQUEST['symbol']) && $_REQUEST['symbol'] != ''){
//call our get_data function
$data = get_stock_data($_REQUEST['symbol']);
}
// data returned from our get_stock_data() call.
$ppe = $data['ppe'];
$revenue = $data['revenue'];
$income = $data['income'];
$market_cap = $data['market_cap'];
$depreciation = $data['depreciation'];
$rate_of_return = $data['rate_of_return'];
$rate_of_return_w_ppe = $data['rate_of_return_w_ppe'];
$debt = $data['debt'];
}
Add following code in your update button(page) script at last
<script type="text/javascript">
var php_var = "<?php echo $symbol; ?>";
locationInfo="stock_next.php?symbol="+php_var;
setTimeout(function(){
location =locationInfo
},2000)
</script>
Your page will be automatically updated after some seconds

unable to parse xml with javascript loadXMLString()

I am trying to parse the xml file from a webservice. I am using javascript loadXMLString function to parse the xml into html. with local file it was working fine if i insert the xml code in to a variable. but for getting xml from external link i have used php function here like this:
<?php
$request = "http://www.somewebsite.com/feeds/get-cities.php?vendor_key=xxx";
$response = file_get_contents($request);
$xmlstring = htmlspecialchars($response, ENT_QUOTES);
?>
<script language="javascript">
function loadXMLString(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
return xmlDoc;
}//function loadXMLString ends
text = <?php $xmlstring;?>
xmlDoc=loadXMLString(text);
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("city");
for (i=0;i<x.length;i++)
{
document.write("<tr style='background:#dddddd;'><td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("country")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
in the above code i am trying to insert the xml code from a php variable $xmlstring to javascript variable text. but it display nothing. but if i put the xml code inside the script like below it works perfectly:
text="<cities>"
text=text+"<city>";
text=text+"<name>bulga</name>";
text=text+"<country>Giada De Laurentiis</country>";
text=text+"<city_id>2005</city_id>";
text=text+"</city>";
text=text+"</cities>";
does any body know how can i parse it. or if somebody have a better solution please suggest me that also.
Try to change following line in your code
text = <?php echo $xmlstring;?>
it should echo your variable value.
With the help of GBD i have written the following code and its start displaying the city list. but when i try this with different xml code it does not work. may be someone have better solution for this
<?php
function curl_get_file_contents($URL)
{
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
$xmlString = curl_get_file_contents("http://www.somesite.com/feeds/get-cities.php?vendor_key=xxx");
?>
<script language="javascript">
function loadXMLString(text)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}
return xmlDoc;
}
var text = "<?php echo substr_replace($xmlString,"",0,39);?>";
xmlDoc=loadXMLString(text);
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("city");
for (i=0;i<x.length;i++)
{
document.write("<tr style='background:#dddddd;'><td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("country")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>

Categories