preg_match not Working php and java script - javascript

I need to extract a value (id value) from html web page .
this value is included in JavaScript code.
my scraper php >
<?php
if (isset($_POST['submit']))
{
$handle = fopen($_POST['website_url'], "r");
if ($handle)
{
while (!feof($handle))
{
$text .= fread($handle, 128);
}
fclose($handle);
}
$result = preg_match('(?<=id: ")(.*)(?=",)', $text);
echo $result;
}
?>
My javaScript Code is >
<script type="text/JavaScript">
var geoInstance = gioFinder("geo");
geoInstance.setup({
id: "126568949", // i need this
geometre: "triangle",
type: "html",
image: 'https://example/126568949.jpg',
});
</script>
I need to extract id value but preg_match not working

It looks like you are missing the /s wrapping your pattern.
You will also want to set the matches array
$result = preg_match('/(?<=id: ")(.*)(?=",)/', $text, $matches);
echo $matches[0];

Related

How can I use PHP values in .js Extension Files?

var Facilites = {
"91": {
"facilites": "Wifi:Fans:AC",
"RoomcatgId": "91"
},
"95": {
"RoomcatgId": "95",
"facilites": "Air Cooler:Daily Newspaper:Wifi:Fans"
}
}
In Above code I want to Add PHP Wordpress Code in facilities field, But How Can I put PHP Codes in .js Extension Files?
<?php
$facilities = get_field_object('facilities');
value = $facilities['value'];
echo "<span>";
if( $value ):
foreach( $value as $val ):
$fac = implode( ":", $facilities['choices'][ $val ] );
echo $fac;
endforeach;
endif;
echo "</span>";
?>
in the field facilities I want to add above PHP code like:
"91": { "facilities": "<?php #php code here ?>" }
The result depends on how your code/files work together but it is possible. You don't need to add PHP code to your .js file. That file can't process PHP code. Unless the javascript code is in the .php file as well.
Try this (I just copied your code, didn't check it):
<?php
$facilities = get_field_object('facilities');
value = $facilities['value'];
$myJSValues = "";
if( $value ):
foreach( $value as $val ):
$fac = implode( ":", $facilities['choices'][ $val ] );
$myJSValues .= $fac;
endforeach;
endif;
?>
<script>
var myValues = <?php echo $myJSValues; ?>
</script>
in your .js file use myValues

extract JavaScript value from page web by (PHP)

i need to extract a value (id value) from html web page . this value
is included in JavaScript code .
<script type="text/JavaScript">
var geoInstance = gioFinder("geo");
geoInstance.setup({
id: "126568949", // i need this
geometre: "triangle",
type: "html",
image: 'https://example/126568949.jpg',
});
</script>
my code php is
<?php
$filename = "https://examlpe.com";
$handle = fopen($filename, "r");
if ($handle) {
while (!feof($handle)) {
$text. = fread($handle, 128);
}
fclose($handle);
}
// How can you do
//right answer is .
$result = preg_match('/(?<=id: ")(.*)(?=",)/', $text, $matches);
echo $matches[0];
//end
?>
You could read the file as a string and then use RegEx to find the specific value.
An example for your case could be the RegEx pattern (?<=id: ")(.*)(?=",).
Then use preg_match: preg_match('(?<=id: ")(.*)(?=",)', $html);

Can't read csv in PHP and pass it to javascript in a html file

Environment
Windows 8.1 64bit
Google Chrome
What I'm trying to do
Ultimate goal
Make a pet monitoring system using Raspberry Pi. Create a webpage where you can check streaming image of a pet and the temperature and humidity.
Current issue
Can't read csv data (temperature and humidity) using PHP and pass it to javascript in a html file.
The following gives me a blank page.
test.html
<?php
$data = array();
$fp = fopen('temphumid.csv', 'r');
$row = fgetcsv($fp); // skip the header
while ($row = fgetcsv($fp)) { $data[] = sprintf("['%d', %d, %d] ", $row[0], $row[1], $row[2]); }
$str = implode(', ' . PHP_EOL, $data);
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ ['day', 'avg_temp', 'avg_humid'],
<?php $str; ?>
]);
var options = { title: 'This is a test graph' };
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 80%; height: 400px;"></div>
</body>
</html>
temphumid.csv is in the same directory as test.html.
temphumid.csv
dateandtime,temp,humid
1,20.0701749938488,48.0275514992728
2,20.2401044696121,57.2354245801184
3,19.1474087424506,45.5657495890199
4,18.8319188605772,62.4405658353862
5,20.8854516366497,46.5185590247232
6,20.7459481702926,47.4137986506082
7,20.9609524855751,48.5064890268627
8,17.0936718055156,46.1276393517355
9,18.4273511669417,42.4825830307023
10,20.9669696456074,51.5502032331834
I tried a lot of things including adding echo to php clause, hard-coding a sample array in javascript, etc... in vain.
Changing the line of <?php echo $str; ?> to [0, 5, 4], [1, 9, 10], [2, 20, 23] works fine. So there's something wrong with PHP but I can't figure out what it is.
I also referred to this post.
- How to pass variables and data from PHP to JavaScript?
But this wasn't helpful.
Also, the javascript console told me the following message.
The console tells me Uncaught SyntaxError: Unexpected token <
How can I solve this issue? Thanks in advance.
update1
I added echo and ran the program in a web server in Raspberry Pi. However, I still see a blank page and Uncaught SyntaxError: Unexpected token < on console.
update2
I changed the extension to php and now it works fine. Thanks, folks!
Replace <?php $str; ?> with <?php echo $str; ?>, change the extension of your file to .php instead of .html, and everything will work well.
Maybe it's because the php file doesn't have a .php extension. Try renaming test.html in test.php.
Some similar code I wrote:
$seperator = $_POST['seperator'];
$escape = $_POST['escape'];
$default_val = $_POST['default_val'];
$files = $_FILES['filesToUpload']['name'];
$files_array = array();
//no files selected
if ($files[0] == "") {
echo "You have to select at least 1 file";
exit();
}
//preprocess by creating an array per file with it's path and name
$count = 0;
foreach ($files as $file) {
$current_file = array();
$current_file['name'] = $file;
$current_file['path'] = $_FILES['filesToUpload']['tmp_name'][$count];
$files_array[$file] = $current_file;
++$count;
}
$translation_array = array();
$languages = array();
foreach ($files_array as $file_key => $file_value) {
$text_file = file($file_value['path']);
$languages[] = $file_value['name'];
foreach ($text_file as $line_number => $line) {
$line = rtrim($line, "\n");
$line_parts = explode('=', $line);
$translation_key = $line_parts[0];
if ($file_value['name'] != 'brndportal.properties') {
$translation_array[$translation_key][$file_value['name']] = $line_parts[1];
} else {
$translation_array[$translation_key][$file_value['name']] = $line_parts[0];
}
}
}
$translation_csv = fopen("files/translation.csv", "w") or die("Unable to open file!");
//headers
$txt = "key" . $seperator;
foreach ($files as $file) {
$txt .= $file . $seperator;
}
$txt .= "\n";
fwrite($translation_csv, $txt);
//translations
foreach ($translation_array as $translation_key => $translation_arr) {
if (array_key_exists('brndportal.properties', $translation_array[$translation_key])) {
$txt = '';
$txt .= $translation_key . $seperator;
foreach ($languages as $language) {
if(array_key_exists($language, $translation_arr)) {
$translation_value = $translation_arr[$language];
}
else {
$translation_value = $default_val;
}
if (strpos($translation_value, $seperator) !== false) {
$translation_value = $escape . $translation_value . $escape;
}
$txt .= $translation_value . $seperator;
}
$txt .= "\n";
fwrite($translation_csv, $txt);
}
}
fclose($translation_csv);
It reads 1 or more CSV files and parse the lines. You can insert you own separator and stuff.
I think it would be best to read everything to arrays and serialize it to JSON, that way you can pass it to javascript with an ajax call. I'd suggest using jQuery for that part.
I had the same difficulty with Uncaught SyntaxError: Unexpected token < on the console.
The <?php echo $str; ?> solution works for certain variables. I had an array though.
So I used var myArray = <?php echo json_encode($myArray); ?> and it worked.

HTML Escaping/Encoding in Javascript/PHP

I have multiple pages of html code saved into a database. I want a file to be able to flip through each of these pages without reloading.
I created a PHP file to pull all the pages into a database.
The page shows the first page and navigation buttons.
There is also javascript to put all the other pages into an array so I can quickly switch pages.
var pages = new Array();
<?php foreach ($coursePages as $page): ?>
pages[pageCount] = "<?php echo ($page['body']) ?>";
pageCount++;
<?php endforeach ?>
My problem is creating the javascript array. How can I escape the data from the echo properly so it can eventually change the page content using the following:
$(document).ready(function() {
$('.navNext, .navPrevious').click(function({
if ($(this).hasClass('navNext')) {
page++;
if (page > pageCount) {
page = 0;
}
} else {
page--;
if (page < 0) {
page = 0;
}
}
$('.page').html(pages[page]);
}))
});
Anytime you send values dynamically from PHP to JavaScript, you can simply use json_encode(). It will always produce valid JavaScript and handle all data types. Example:
<script>
var a = <?php echo json_encode($var)?>;
</script>
you can use this function to escape js values:
function js_escape_string($str)
{
$str = str_replace("\\", "\\\\", strval($str));
$str = str_replace("'", "\\'", $str);
$str = str_replace("\r", "\\r", $str);
$str = str_replace("\n", "\\n", $str);
$str = str_replace("\t", "\\t", $str);
$str = str_replace("</script>", "</'+'script>", $str);
return $str;
}
NOTE: use single quote ' around JS values, like:
<script>
var a = '<?php echo js_escape_string(....); ?>';
</script>

Should this file be loaded as a valid .js file?

I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>

Categories