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();
}
Related
I want to open a new page and transfer data from an array. Using the name of the image seemed like the easiest way so that's what i want to do.
on the page i want to call it
function meghiv($img)
{
$be=$img.alt;
echo $be;
session_start();
$_SESSION['kod'] = $be;
}
for($j=0;$j<4;$j++)
{
echo ' <img src="'.$nevek[$i].'.png" class="card-img-top " alt="'.$i.'" onclick="meghiv(this)"> ';
$i++;
}
on the new page
<?php
session_start();
echo $_SESSION['kod'];
?>
I don't know if it answers your question but try using javascript to load the image name into your php file
let images = document.querySelectorAll('.card-img-top'); // returns NodeList
let img_list = [...images]; // converts NodeList to Array
img_list.forEach(div => {
div.addEventListener("click", function(e){
e.preventDefault()
let alt = div.getAttribute("alt")
window.open(`https://link.here/?alt=${alt}`, "_blank");
})
});
Then in your php file
$image_name = $_GET['alt'];
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.
We load html by url. After that creating DOMDocument
libxml_use_internal_errors(true); // disable errors
$oHtml = new DOMDocument();
if (!$oHtml->loadHTML($this->getHtml($aData['href']))) {
return false;
}
Next step is to delete fancybox or other popUp links... In our case image code is
<a onclick="return hs.expand(this)" href="http://domain.com/uploads/09072014106.jpg">
<img title="Some title" alt="Some title" src="http://domain.com/uploads/thumbs/09072014106.jpg">
</a>
And we execute our method for it ...
$this->clearPopUpLink($oHtml); // delete parent <a tag....
Method...
private function clearPopUpLink($oHtml)
{
$aLink = $oHtml->getElementsByTagName('a');
if (!$aLink->length) {
return false;
}
for ($k = 0; $k < $aLink->length; $k++) {
$oLink = $aLink->item($k);
if (strpos($oLink->getAttribute('onclick'), 'return hs.expand(this)') !== false) {
// <a onclick="return hs.expand(this)" href="http://domain.com/uploads/posts/2014-07/1405107411_09072014106.jpg">
// <img title="Some title" alt="Some title" src="http://domain.com/uploads/posts/2014-07/thumbs/1405107411_09072014106.jpg">
// </a>
$oImg = $oLink->firstChild;
$oImg->setAttribute('src', $oLink->getAttribute('href')); // set img proper src
// $oLink->parentNode->removeChild($oLink);
// $oLink->parentNode->replaceChild($oImg, $oLink);
$oLink->parentNode->insertBefore($oImg); // replacing!?!?!?!
// echo $oHtml->ownerDocument->saveHtml($oImg);
}
}
}
Now questions... This code is working BUT I don't get WHY! Why when clearPopUpLink() done with all "images" it has not OLD code with tags? I tried to use (in first time when start investigation) ->insertBefore(), after that ->removeChild(). First is add simple (edited) image BEFOR current image (with <a>), after that delete old node image (with <a>). BUT! It doesn't work, it was doing only on each second (each first was done correctly).
So, let me ask simple question, how to do it in right way? Because I don't think that code below (clearPopUpLink) is correct enough... Please suggest your solutions.
Hmm, I would use the trustee XPath for this and make sure the anchor gets removed; the code you've shown doesn't exactly make that obvious (I haven't tested it).
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//a[contains(#onclick, "return hs.expand(this)")]/img') as $img) {
$anchor = $img->parentNode;
$anchor->parentNode->insertBefore($img, $anchor); // take image out
$anchor->parentNode->removeChild($anchor); // remove empty anchor
}
echo $doc->saveHTML();
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
I'm making a form in php. I want the visitor to either upload an image (that part is done) or select one from the uploaded files. Is there any cool jQuery/php script that will solve this?
I'm thinking a small dialog that shows all the images from a selected folder. When the visitor clicks on foo.jpg (with thumbnail) the value in the text field would be "foo.jpg"
Any ideas?
Thanks!
Just scan the images directory like that:
<?php $dir = '/path/to/dir';
$files1 = scandir($dir);
foreach ($files1 as $value) {
echo '<p class="images">'.$value.'</p>';
echo '<img class="clickableimg" id="'.$value.'" src="path/to/'.$value.'" />';
} ?>
And you can add event on class 'images':
<script>
$(".images").click(function() {
var choosenpic = $(this).html();
$("#yourinputfieldID").val(choosenpic);
});
$(".clickableimg").click(function() {
var choosenpic = $(this).attr('id');
$("#yourinputfieldID").val(choosenpic);
});
</script>