I am using Simple HTML Dom Parser to scrape a script tag from a webpage and then attempting to parse certain data from said tag using preg_match_all(). However, when I print preg_match_all, no results are returned.
Below is the code I'm using:
<head>
<?php
require_once "toolkit/http.php";
require_once "toolkit/web_browser.php";
require_once "toolkit/simple_html_dom.php";
?>
</head>
<body>
<?php
$prod_url = 'http://www.domain.com/subpage.html';
$html = file_get_html($prod_url);
$script = $html->find('script', 17);
//echo $script;
preg_match_all('(?<=\d":)\w++', $script, $matches);
print_r($matches);
?>
</body>
I can see that the HTML Simple Dom code is working correctly, as I get the results I expect when echoing the $script variable. The results are:
<script type="text/javascript">
var PRODUCT_JSON = {
"Def":{
"default":202705111,
"Listing:[{
"label":"Includes",
"options":[
{label:"All", id: "884"},
{label:"None", id: "485"},
]
}],
"Lookup":{
"1":202705111,
"0":202493236
}
}
};
</script>
So, the issue appears to be with the regex I'm using in preg_match_all(). The goal of the regex is to return the two numbers, 202705 and 202493, near the end of the script tag. It may have to do with escaping the double quote or parentheses, though I've also tried preg_match_all('\(?<=\d\":\)\w++', $script, $matches); with the same result. Any ideas on what I'm doing wrong?
If you keep forgetting about delimiters, you can use T-Regx, which automatically adds delimiters.
$matches = pattern('(?<=\d":)\w++')->match($script)->all();
Related
I have the following piece of code which I partly got from another thread in SO:
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
$origadd = $_SESSION["OriginAdd"] // $_SESSION["OriginAdd"] has a value "rueFrédéricMistral";
echo $origadd; // This displays rueFrédéricMistral
?>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var source = <?php echo json_encode($origadd); ?>;
alert(source); // This displays null
</script>
</head>
....
....
</html>
As I have mentioned in the comments, the echo statement gives me the original string. However, the alert box in JS gives me a null value because of which the subsequent code is failing.
The problem here is an encoding issue and the accents played a major role here. Had the string been just "abc" for example, it would have alerted it properly. Everything needs to be UTF-8 if you want both contents to show up properly.
Therefore, you need to change the file's encoding to UTF-8 and also set the header as UTF-8.
This was tested with successful results.
<?php
header('Content-Type: text/html; charset=UTF-8');
$origadd = "rueFrédéricMistral";
echo $origadd; // This displays rueFrédéricMistral
?>
<script type="text/javascript">
var source = <?php echo json_encode($origadd); ?>;
alert(source);
</script>
Note: $origadd = "rueFrédéricMistral"; was used from the original post holding that value.
https://stackoverflow.com/revisions/46956093/1
where I stated that the string needed to be wrapped in quotes, otherwise it would have been treated as a constant. (To which someone deleted that comment I placed as being the first comment).
Note:
Using header('Content-Type: text/html; charset=ISO-8859-1'); instead of header('Content-Type: text/html; charset=UTF-8');, your initial HTML would have shown you rueFrédéricMistral instead of the intended rueFrédéricMistral.
Edit:
As said by the OP, my mentioning to quote it would have also worked.
var source = '<?php echo $origadd; ?>';
As per my comment above.
If you use var source = '<?php echo $origadd; ?>'; as my example and quoting it (something you didn't do), you will see your data is there.
Is there a way to search the PHP content body while it is being parsed by PHP for certain keywords, so I can include CSS and JS files based on the presence of those keywords before the page is being served?
If PHP would have a variable like $_CONTENT_BODY where it outputs the parsed page into, then I could search for keywords like in this example:
if(stripos($_CONTENT_BODY, 'usetinymce') !== false)) echo '<script type="text/javascript" src="http://a.host.com/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>';
You could use ob_start(); and $text = ob_get_contents();. Just make sure that you process these properly, check out http://php.net/manual/en/book.outcontrol.php.
You can get the page itself and parse it.
<?php
if (!isset($_GET['doNotCallMeAgain']) || $_GET['doNotCallMeAgain'] !== 1) {
$urltothisfile = 'urltothefilehimself'+'?doNotCallMeAgain=1';
$result = file_get_contents ($urltothisfile); //in $result you will get your page as html and you can search in it
} ?>
You can assemble a Variable which you can search and output at the End.
$_CONTENT_BODY = 'here ';
$_CONTENT_BODY .= 'is some ';
$_CONTENT_BODY .= 'content.';
if(stripos($_CONTENT_BODY, 'some')){
// do whatever you like
}
You can include another php file and get the results with ob_start/ob_get_clean()
ob_start();
include 'myfile.php';
$_CONTENT_BODY = ob_get_clean();
But you will encounters some problems, like white pages on some php errors.
It is better to build your app more logicaly instead of doing some dirty search & replace.
I have read the following posts, but they are a little over the top for me. I think I'm trying to do something fairly simple, and would like some guidance.
How to pass variables and data from PHP to JavaScript?
passing PHP variables across javascript windows.open to another PHP page
Posting a php variable to a new window
Here is the case:
I have a php script which is very simple, it calls another script and passes 2 variables:
<?php
echo '<script type="text/javascript" language="javascript">
window.open("http://callpage.com/utils/cdr.php?callernum=123456789&calltime=2017-02-22 16:24:12");
</script>';
?>
Note: This is just a "hardcoded" example.
The next script, takes those numbers and builds file/url variable.
Lets say
$file = /var/www/html/file.wav
What I'm trying to do open a new window to the effect of :
http://newpage.com/$file
I have read and found that I think the best use is Javascript, but I can't seem to get my variable into the Javascript.
Here is what I would like to get working:
<?php
$file = /var/www/html/file.wav
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/$file");
</script>';
?>
A few notes:
I don't want to "redirect" the old page, I want it to stay open, and the remote page isn't on the same domain
(one is a.domain.com and the other is b.domain.com).
I don't care about window sizes, etc, its a wav file that I'm expecting the browser to just play with a simple Browser default interface for Wav.
if I understood correctly what you want, you have to concatenate the string with the variable in order to be replaceed
<?php
$file = '/var/www/html/file.wav';
echo '<script type="text/javascript" language="javascript">
window.open("http://newpage.com/'.$file.'");
</script>';
?>
Use string interpolation with double quotes for the echo statement and single quotes everywhere inside the javascript:
echo "<script type='text/javascript' language='javascript'>
window.open('http://newpage.com/$file');
</script>";
The interpolated PHP variable $file should be correctly interpreted as a string and the value it holds should be displayed in the URI of your javascript.
Check out this easy to understand info about variable interpolation http://phppot.com/php/variable-interpolation-in-php/
Here is my "final" code snippet:
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$uid = $row['uniqueid'];
foreach(glob($path. "*". $uid. "*") as $file) {
$link = "http://newpage.com$file";
echo "<script type='text/javascript' language='javascript'>
window.open('$link');
</script>";
}
}
I am developing a web that has to show an sql view, so I did the query with PHP, but I have to show the result in charts, and I am trying to use the google geochart. So basically what I want to do is:
Select the data from an SQL view with PHP.
Get the data from PHP into a javascript variable so I can use it in the chart.
Get the value of the javascript variable to put in the google chart api, so it show what I want.
So far, I've got the point 1 and the point 2 (I think) done. But when I am trying to use the javascript variable again in another part of the code it has no value, so no data is showing, I am getting undefinedon the explorer.
Relevant Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?php
//connections and stuff
$tsql="SELECT count(*) as Qty, ShipCountry FROM [Orders Qry] group by ShipCountry"; // yes, is the Northwind database example
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to query table: ".$tsql);
}
else
{
$json=array();
$i=0;
echo "<script type='text/javascript'> var countries = []; </script>";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";
$i=$i+1;
}
//echo "<h1>". $json["ShipCountry"] ."</h1>"; //I was testing, so the problem is not in retrieving the data from the database.
sqlsrv_free_stmt($stmt);
}
?>
<p>
<script type="text/javascript">
document.write(countries[0]);
</script>
</p>
</body>
</html>
You forgot to quote $row['ShipCountry'] (seems to be a string);
echo "<script> countries[".$i."]= '". $row['ShipCountry'] ."';</script>";
Note the new quotes.
You might want to consider using AJAX to query a different file from within your javascript, cf. http://www.w3schools.com/ajax/ajax_php.asp.
If you have your PHP file return JSON to the AJAX request, javascript will have an object that it understands and you can use it there. This way you can have all your javascript in one place. E.g. this pseudo code:
Javascript.js
function gimmeACountry(i){
var countries = AJAX.get('countries.php');
return countries[i];
}
PHP.php
<?php
$result = mysql_stuff(...);
print json_encode(result);
?>
HTML
<html>
<head>
<script src='Javascript.js'>
</head>
<body onload="document.write(gimmeACountry(0));">
</body>
</html>
If you really want to use just one file, a few thoughts:
You don't need to open and close a statement every time you write javascript. All of your PHP could be embedded in one.
You can output most of your javascript outside of the block, instead of echoing everything. I think the PHP is clearer then. E.G.
<script>
<?php $foo = 'bar'; ?>
var foo = <?php echo $foo ?>;
document.write(foo); // writes 'bar'
</script>
If you are still have scope issues, you can try adding your variable to the window object, e.g.
window.countries = []
This might be problematic if you end up doing more stuff with javascript later. I really do recommend you use AJAX.
You should use push method and Array() Construct
var countries = [];//nope
var countries = new Array();//yep
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";//nope
echo "<script> countries.push(".$row['ShipCountry'].");</script>";//yep
push method documentation
Distributing javascript over two blocks works fine:
<html xmlns="http://www.w3.org/1999/xhtml">
<head />
<body>
<script>
countries = ['foo'];
</script>
<script type="text/javascript">
document.write(countries[0]);
</script>
</body>
</html>
But the problem is that your PHP isn't generating valid java script. Have a look at your browser's JS console, and you'll see ReferenceErrors because you didn't quote the country names.
I am using a javascript slide show on my index page. Instead of the array being static, I want to build the array with PHP and add it with something like and include statement. Since the array is inside the javascript I am unsure how best to do this. Here is a sample of the array:
var fadeimages=new Array()
fadeimages[0]=["pics/fade_pic_1.jpg", "", ""]
fadeimages[1]=["pics/fade_pic_2.jpg", "", ""]
fadeimages[2]=["pics/fade_pic_3.jpg", "", ""]
And here is the PHP file that builds the array. It works great. I just don't know how to place it in the javascript code:
<?php // Build fadepic array for index page
$x=0;
foreach (glob("pics/*.*") as $filename) {
$filename = substr($filename, 20); //gets just the file name
echo "fadeimages[".$x."]=[\"pics/".$filename."\", \"\", \"\"]<br>";
$x++;
} ?>
Thank you in advance for any help you can give me!
You can use json_encode() for this.
<?php
//buildfadepic.php
$result = array();
foreach (glob("pics/*.*") as $filename) {
$result[] = array("pics/".$filename, "", "");
}
print json_encode($result);
This will give you valid JSON (and hence valid JavaScript). If you want to mix JavaScript and PHP, you should be able to do it like this now
var fadeimages = <?php include "buidfadepic.php"; ?>;
Since buidfadepic.php will give you a result like this
[ ["pics/foo.jpg", "", ""], ["pics/bar.png", "", ""], ...]
Or if you have both in the same file, simply print/echo instead of include as suggested in the comments.
The right way, as the comments said would be using json_encode.
For example:
Server
<?php
$files = array('file1.jpg', 'file2.jpg', 'file3.jpg');
$view->assing_var('files', $files); // if you're separating the view from the php, else just do return for including
View (client):
<script type="text/javascript">
var images = <?=json_encode($files)?>;
</script>
I agree with other posters that JSON would be a nice clean way to do this. But you don't necessarily have to, you can also include the array straight away:
<script type="text/javascript">
var fadeimages=new Array();
<?php
echo "fadeimages[0] = ...;"; // Include code to create array
?>
</script>
Just to clarify (based on the comments we seem to have a bit of misunderstanding): you can put PHP code inside <script> tags. After all, the PHP code is run server-side and the client that runs the JavaScript will also see the resulting output. So as long as your PHP script does not produce syntax errors in the JavaScript you should be OK.
An alternative approach, if the script becomes very large, is to include your PHP script as an external JavaScript:
<script type="text/javascript" src="list_fade_images.php"></script>