3 hours till now and i am tring to figure this out but now luck.
i have a page it content consist of several html table each one has certain td
where it look like this
<td style="padding:0px 0px 0px 5px;" valign="middle"><span class="lshevent">team a - team b </span></td>
i want to make this td as hyperlink when someone click this Td open the whole table in new window .
my page source is retreived from remote page through file get contents as below
<?php
//Get the url
$url = "http://remotesite/pages/page1.html";
$html = file_get_contents($url);
$doc = new DOMDocument(); // create DOMDocument
libxml_use_internal_errors(true);
$doc->loadHTML($html); // load HTML you can add $html
$elements = $doc->getElementsByTagName('tbody');
$toRemove = array();
// gather a list of tbodys to remove
foreach($elements as $el)
if((strpos($el->nodeValue, 'desktop') !== false) && !in_array($el->parentNode, $toRemove, true))
$toRemove[] = $el->parentNode;
foreach($elements as $el)
if((strpos($el->nodeValue, 'Recommended') !== false) && !in_array($el->parentNode, $toRemove, true))
$toRemove[] = $el->parentNode;
// remove them
foreach($toRemove as $tbody)
$tbody->parentNode->removeChild($tbody);
echo str_replace('</h3><table','<table',$doc->saveHTML());
?>
try putting a onclick="openInNewWindow();" and in that function call ajax with your code, well also a possibility would be to just put an ID on and $('#<your_id>').click(function(){}); and when ajax will return success the window.open();
sorry, well, roughly it will look like this:
html -> <td id="open"> or <td onclick="openWindow();">
js:
$(function(){
$('#open').click(function(){
$.ajax({
type : 'POST',
data: {},
dataType : 'html',
url : '/remotesite/getSite', //here goes the link to your php function(if you are using MVC logic then it will look like this)
success: function(data){
myWindow=window.open('','','width=200,height=100');
myWindow.document.write(data);
}
});
});
});
or
function openWindow(){
//copy the $.ajax function from above here
}
and in php just create a controller (that depends if you have MVC logic on your webpage if not then the actual path to the file you are using)
public function getSite(){
//your code here and echo the template or html code where
//where you have your table like echo $html_code;
}
EDITED:
Sorry that i didn't post the code before
Related
I am trying to make an incredibly simple ajax call, but it wont work.
Here is the php side called by ajax( This returns the correct response )
<?php
$returnValue = '';
$allUploads = array_slice(scandir('./uploads'), 2);
$returnValue .= '<table>';
foreach ($allUploads as $upload) {
$returnValue .= '<tr><a href ="/uploads/' . $upload . '>' . $upload . '</a></tr>';
}
$returnValue .= '</table>';
echo($returnValue);
?>
And here is the javascript thats letting me down
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange =
function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
document.getElementById("filedisplaytable").innerHTML = this.responseText;
}
};
xhttp.open("GET", "listuploads.php", true);
xhttp.send();
</script>
Worst thing about this is, that the alert statement is outputting exactly what I want to write:
<table>
<tr>
<a href ="/uploads/DSC001.jpg>DSC001.jpg</a></tr><tr><a href ="/uploads/DSC002.jpg>DSC002.jpg</a>
</tr>
<tr>
<a href ="/uploads/DSC003.jpg>DSC003.jpg</a>
</tr>
</table>
But when I write that into the div it writes the a hrefs 1st followed by an empty table...
Any help is greatly appreciated.... struggling to do such simple things really gets me down
Your HTML is invalid.
An <a> element cannot be a child element of a <tr>.
Only <td> and <th> are allowed there.
The problem you are experiencing is likely the result of the browser attempting to recover from your error by moving the <a> elements to somewhere they are allowed (i.e. outside the table).
Write valid HTML instead. It looks like you don't have a tabular data structure so probably shouldn't be using a table in the first place. A list might be a better bet.
Like Quentin said, your HTML is invalid. <a> tags are allowed in <td> though.
Replace your PHP line of code with this one:
$returnValue .= '<tr><td><a href ="/uploads/' . $upload . '>' . $upload . '</a></td></tr>';
I am new to scraping website and I was interested in getting the ticket prices from this website.
https://www.cheaptickets.com/events/tickets/firefly-music-festival-4-day-pass-2867495
I see the ticket prices in the p#price-selected-label.filters-selected-label tag, but I cant seem to access it. I tried a few things and looked at a few tutorials, but either I get a blank returned or some error. The code is based off http://blog.endpoint.com/2016/07/scrape-web-content-with-php-no-api-no.html
<?php
require('simple_html_dom.php');
// Create DOM from URL or file
$html = file_get_html('https://www.cheaptickets.com/events/tickets/firefly-music-festival-4-day-pass-2867495');
// creating an array of elements
$videos = [];
// Find top ten videos
$i = 1;
$videoDetails = $html->find('p#price-selected-label.filters-selected-label')-> innertext;
// $videoDetails = $html->find('p#price-selected-label.filters-selected-label',0);
echo $videoDetails;
/*
foreach ($html->find('li.expanded-shelf-content-item-wrapper') as $video) {
if ($i > 10) {
break;
}
// Find item link element
$videoDetails = $video->find('a.yt-uix-tile-link', 0);
// get title attribute
$videoTitle = $videoDetails->title;
// get href attribute
$videoUrl = 'https://youtube.com' . $videoDetails->href;
// push to a list of videos
$videos[] = [
'title' => $videoTitle,
'url' => $videoUrl
];
$i++;
}
var_dump($videos);
*/
You can't get it because javascript renders it, so it's not available in the original html that your library get.
Use phantomjs(will execute javascript);
Download phantomjs and place the executable in a path that your PHP binary can reach.
Place the following 2 files in the same directory:
get-website.php
<?php
$phantom_script= dirname(__FILE__). '/get-website.js';
$response = exec ('phantomjs ' . $phantom_script);
echo htmlspecialchars($response);
?>
get-website.js
var webPage = require('webpage');
var page = webPage.create();
page.open('https://www.cheaptickets.com/events/tickets/firefly-music-festival-4-day-pass-2867495', function(status) {
if (status === "success") {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
var myElem = $('p#price-selected-label.filters-selected-label');
console.log(myElem);
});
phantom.exit();
}
});
Browse to get-website.php and the target site, https://www.cheaptickets.com/events/tickets/firefly-music-festival-4-day-pass-2867495 contents will return after executing inline javascript. You can also call this from a command line using php /path/to/get-website.php.
I'm working on a tool to replace tagged areas in a html document. I've had a look at a few php template systems, but they are not really what I am looking for, so here is what I am after as the "engine" of the system. The template itself has no php and I'm searching the file for the keyword 'editable' to set the areas that are updatable. I don't want to use a database to store anything, instead read everything from the html file itself.
It still has a few areas to fix, but most importantly, I need the part where it iterates over the array of 'editable' regions and updates the template file.
Here is test.html (template file for testing purposes):
<html>
<font class="editable">
This is editable section 1
</font>
<br><br><hr><br>
<font class="editable">
This is editable section 2
</font>
</html>
I'd like to be able the update the 'editable' sections via a set of form textareas. This still needs a bit of work, but here is as far as I've got:
<?php
function g($string,$start,$end){
preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
$out = array();
foreach($m[1] as $key => $value){
$type = explode('::',$value);
if(sizeof($type)>1){
if(!is_array($out[$type[0]]))
$out[$type[0]] = array();
$out[$type[0]][] = $type[1];
} else {
$out[] = $value;
}
}
return $out;
};
// GET FILES IN DIR
$directory="Templates/";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$i=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$files[$i]=$file;
//echo $files[$i]."<br>";
$i++;
}
};
//echo $files[0];
?>
<div style="float:left; width:300px; height:100%; background-color:#252525; color:#cccccc;">
<form method="post" id="Form">
Choose a template:
<select>
<?php
// Dropdown of files in directory
foreach ($files as $file) {
echo "<option>".$file."</option>"; // do somemething to make this $file on selection. Refresh page and populate fields below with the editable areas of the $file html
};
?>
</select>
<br>
<hr>
Update these editable areas:<br>
<?php
$file = 'test.html'; // make this fed from form dropdown (list of files in $folder directory)
$html = file_get_contents($file);
$start = 'class="editable">';
$end = '<';
$oldText = g($html,$start,$end);
$i = 0;
foreach($oldText as $value){
echo '<textarea value="" style="width: 60px; height:20px;">'.$oldText[$i].'</textarea>'; // create a <textarea> that will update the editable area with changes
// something here
$i++;
};
// On submit, update all $oldText values in test.html with new values.
?>
<br><hr>
<input type="submit" name="save" value="Save"/>
</div>
<div style="float:left; width:300px;">
<?php include $file; // preview the file from dropdown. The editable areas should update when <textareas> are updated ?>
</div>
<div style="clear:both;"></div>
I know this answer is a little more involved, but I'd really appreciate any help.
Not sure if i correctly understand what you want to achieve. But it seems I would do that in jquery.
You can get all html elements that has the "editable" class like this :
$(".editable")
You can iterate on them with :
$(".editable").each(function(index){
alert($(this).text()); // or .html()
// etc... do your stuff
});
If you have all your data in a php array. You just need to pass it to the client using json. Use php print inside a javascript tag.
<?php
print "var phparray = " . json_encode($myphparray);
?>
I think it would be better to put the work on the client side (javascript). It will lower the server work load (PHP).
But as I said, I don't think I've grasped everything you wanted to achive.
I wonder whether someone may be able to help me please.
I'm using this page to allow users to view a gallery of their uploaded images.
Upon upload, the images are saved in this filepath UploadedFiles/userid/locationid/image and the details of the image i.e. name, description etc are saved in an XML file called files.xml which located in the same directory as the images. An extract of this is shown below:
<?xml version="1.0" encoding="utf-8" ?>
- <files>
<file name="AC-0003749-Clark_145520.jpg" source="AC-0003749-Clark_145520.jpg" size="3873" originalname="AC-0003749-Clark_145520.jpg" description="No description provided" userid="1" locationid="1" />
</files>
The gallery gives additional functionality to the user by, via the icon under each image, the ability to delete each image. This is done via the following code:
Icon click Event
<script type="text/javascript">
Galleria.ready(function() {
this.$('thumblink').click();
$(".galleria-image").append(
"<span class='btn-delete ui-icon ui-icon-trash'></span>");
$(".btn-delete").live("click", function(){
var img = $(this).closest(".galleria-image").find("img");
// send the AJAX request
$.ajax({
url : 'delete.php',
type : 'post',
data : { image : img.attr('src') },
success : function(){
alert('Deleting image... ');
img.parent().fadeOut('slow');
}
});
return false;
});
});
</script>
delete.php - Amended Code
<?php
if (!empty($_POST)) {
$image = $_POST['image'];
if (file_exists($image)) {
unlink($image);
}
}
$doc = new DOMDocument;
$doc->load('files.xml');
$thedocument = $doc->documentElement;
$list = $thedocument->getElementsByTagName('files');
$nodeToRemove = null;
foreach ($list as $domElement){
if ($attrValue == '$image') { $domElement->parentNode->removeChild($domElement); }
}
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
echo $doc->saveXML();
?>
The deletion of the physical image works fine, but I'm having great difficulty in working out how to delete the relevant child node. Although I receive no error message the node is not deleted. I have received some guidance here from this site about how to go about this, i.e. via PHP XML DOM, but to be honest the more I read about this, the more I get confused. I just can't seem to get my head around it.
I just wondered whether someone could have a look at this please and let me know where I've gone wrong.
Many thanks and kind regards
To remove a node that was found with getElementsByTagName you can use the following to remove it:
if (!empty($_POST)) {
$image = $_POST['image'];
if (file_exists($image)) {
unlink($image);
}
$doc = new DOMDocument;
$doc->load('files.xml');
// iterate over all tags named <file>
$list = $doc->getElementsByTagName('file');
foreach ($list as $domElement) {
// check whether attribute 'source' equals $image
if ($domElement->getAttribute('source') == $image) {
// remove the node
$domElement->parentNode->removeChild($domElement);
}
}
echo $doc->saveXML();
}
im being played by php and DomDocument.... basically i have some html saved in db. With anchor tags with different urls.... i want to force anchor tag hrefs not within allowedurl list to be replaced with #
eg
$allowed_url_basenames = array('viewprofile.php','viewalbum.php');
sample content from db1
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top">
Edrine Kasasa has
</td>
<td valign="top">
invited 10 friend(s) to veepiz using the Invite Tool
</td>
</tr>
</tbody>
i want a php function that will leave first anchor tag href intact and change the second to href='#'.
This should be pretty straight-forward.
First, let's grab all of the anchor tags. $doc is the document you've created with your HTML as the source.
$anchors = $doc->getElementsByTagName('a');
Now we'll go through them one-by-one and inspect the href attribute. Let's pretend that the function contains_bad_url returns true when the passed string is on your blacklist. You'll need to write that yourself.
foreach($anchors as $anchor)
if($anchor->hasAttribute('href') && contains_bad_url($anchor->getAttribute('href'))) {
$anchor->setAttribute('href', '#');
}
}
Tada. That should be all there is to it. You should be able to get the results back as an XML string and do whatever you need to do with the rest.
Thanx Charles.... came up with this
function contains_bad_urls($href,$allowed_urls)
{
$x=pathinfo($href);
$bn=$x['filename'];
if (array_search($bn,$allowed_urls)>-1)
{
return false;
}
return true;
}
function CleanHtmlUrls($str)
{
$allow_urls = array('viewprofile','viewwall');//change these to whatever filename
$doc = new DOMDocument();
$doc->loadHTML($str);
$doc->formatOutput = true;
$anchors = $doc->getElementsByTagName('a');
foreach($anchors as $anchor)
{
$anchor->setAttribute('onclick','#');
if(contains_bad_urls($anchor->getAttribute('href'),$allow_urls))
{
$anchor->setAttribute('href', '#');
}
}
$ret=$doc->saveHTML();
return $ret
}