Copying a Word and saving it as a Variable - php

I am building an online spanish dictionary. I obtain the definitions legally from another site. For specific words the user may search for, a list of suggestions comes up.
If you click on any of those suggested words, error page pops up: http://verbum.xtrweb.com/verbumpost.php?word=boedo&word0=hola . How can I make those listed words run through the code pasted below: (1) retrieve definition (2) change style.
I know that a unique URL exists for every one of those suggested words (inspect element). If you paste together that code with the original site's URL parameters, you get what I need.:
"http://lema.rae.es/drae/srv/search?id=AVNYdnea1DXX2EH9E2mb"
up to "srv/" belongs to site
the rest is from the specific word (in this case, the first suggested, "bordar"
The Process:
<?php
$words = array('word','word0','word1','word2','word3','word4','word5','word6','word7','word7','word9',
'word10','word11','word12',
'word13','word14','word15');
function url_decode($string){
return urldecode(utf8_decode($string));
}
// we'll use this later on for loading the files.
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
// string to replace in the head.
$cssReplace = <<<EOT
<style type="text/css">
//blabla
</style>
</head>
EOT;
// string to remove in the document.
$spanRemove = '<span class="f"><b>.</b></span>';
$styleRemove =
// use for printing out the result ID.
$resultIndex = 0;
// loop through the words we defined above
// load the respective file, and print it out.
foreach($words as $word) {
// check if the request with
// the given word exists. If not,
// continue to the next word
if(!isset($_REQUEST[$word]))
continue;
// load the contents of the base url and requested word.
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
// replace the data defined above.
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = str_replace($spanRemove,"", $contents);
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $data);
// print out the result with the result index.
// ++$resultIndex simply returns the value of
// $resultIndex after adding one to it.
echo "<div id='results' style='
//bla bla
}
?>

I don't think I understand your question, but I do see that you are calling preg_replace on an uninitialized variable - $data.
Maybe you want this instead?
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $contents);
Like I said, I don't fully understand your question, but I do see that as a potential problem.
EDIT:
From your comment, it looks like you want to append the href of the link being clicked to a base url and request that page's data. Can you use jQuery? Like this:
var baseUrl = "http://lema.rae.es/drae/srv/"; // base url
//click function that binds to all anchors within a list item within a ul. in order
//to get more precise, you may need to add some classes or ids
$('ul li a').click(function(){
var src = $(this).prop('href'); //this grabs the href property of the anchor
$(this).find('span').css('propery', 'change to this'); //change css property of span child of this anchor
//or if you want to add a class with styles to the element
$(this).find('span').addClass('class name');
//ajax request to get page data
$.ajax({
type: 'POST',
url: baseUrl+src //appending the query to the base url
}).done(function(data){
//append the returned html to a div, or any element you desire
$('#myelement').append(data);
});
});
Hope this helps. If you need any help with jQuery just let me know.

Related

scraping images from url using php

i am trying to make a page that allows me to grab and save images from another link , so here's what i want to add on my page:
text box (to enter url that i want to get images from).
save dialog box to specify the path to save images.
but what i am trying to do here i want to save images only from that url and from inside specific element.
for example on my code i say go to example.com and from inside of element class="images" grab all images.
notes: not all images from the page, just from inside the element
whether element has 3 images in it or 50 or 100 i don't care.
here's what i tried and worked using php
<?php
$html = file_get_contents('http://www.tgo-tv.net');
preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i',$html, $matches );
echo $matches[ 1 ][ 0 ];
?>
this gets image name and path but what i am trying to make is a save dialog box and the code must save image directly into that path instead of echo it out
hope you understand
Edit 2
it's ok of Not having save dialog box. i must specify save path from the code
If you want something generic, you can use:
<?php
$the_site = "http://somesite.com";
$the_tag = "div"; #
$the_class = "images";
$html = file_get_contents($the_site);
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//'.$the_tag.'[contains(#class,"'.$the_class.'")]/img') as $item) {
$img_src = $item->getAttribute('src');
print $img_src."\n";
}
Usage:
Change the site, tag, which can be a div, span, a, etc. also change the class name.
For example, change the values to:
$the_site = "https://stackoverflow.com/questions/23674744/what-is-the-equivalent-of-python-any-and-all-functions-in-javascript";
$the_tag = "div"; #
$the_class = "gravatar-wrapper-32";
Output:
https://www.gravatar.com/avatar/67d8ca039ee1ffd5c6db0d29aeb4b168?s=32&d=identicon&r=PG
https://www.gravatar.com/avatar/24da669dda96b6f17a802bdb7f6d429f?s=32&d=identicon&r=PG
https://www.gravatar.com/avatar/24780fb6df85a943c7aea0402c843737?s=32&d=identicon&r=PG
Maybe you should try HTML DOM Parser for PHP. I've found this tool recently and to be honest it works pretty well. It was JQuery-like selectors as you can see on the site. I suggest you to take a look and try something like:
<?php
require_once("./simple_html_dom.php");
foreach ($html->find("<tag>") as $<tag>) //Start from the root (<html></html>) find the the parent tag you want to search in instead of <tag> (e.g "div" if you want to search in all divs)
{
foreach ($<tag>->find("img") as $img) //Start searching for img tag in all (divs) you found
{
echo $img->src . "<br>"; //Output the information from the img's src attribute (if the found tag is <img src="www.example.com/cat.png"> you will get www.example.com/cat.png as result)
}
}
?>
I hope i helped you less or more.

PHP redirect but in parent frame

I have a small time url shortner at http://thetpg.tk using a simple php script and MySQL.
What it does is to get the id and matches it in the SQL Database and redirects it to the specified link found in the Database using header().
But if I have a frameset with source as something like http://thetpg.tk redirected link is loaded inside the frame instead of the parent window.
For e.g. look at the page source of
http://thetpgmusic.tk which has the frame source as
http://thetpg.tk/b which further redirects to
http://thepirategamer.tk/music.php .
I want (1) to load (3) as the parent, but just by making changes in the functions in (2) .
So is there a function like
header(Location:http://thepirategamer.tk/music.php, '_parent');
in php, or is there any other way to implement it?
NOTE: I can't change anything in (2).
Thanks in advance ! :)
There are tree solutions that can help you do this:
First solution:
This solution may involve php if you're using echo to generate your html code, when you need to output an a tag, you should make sure to add the atribute target='_parent'
<?php
echo ' Click here ';
?>
problem :
The problem with this solution, is that it doesn't work if you need to redirect in the parent window from a page that you don't own (inside the iframe). The second solution solves this problem
Second solution:
This second solution is totally client-side, wich means you need to use some javascript. you should define a javascript function that addes the target='_parent' in every a tag
function init ()
{
TagNames = document.getElementById('iframe').contentWindow.document.getElementsByTagName('a');
for( var x=0; x < TagNames.length; x++ )
TagNames[x].onclick = function()
{
this.setAttribute('target','_parent');
}
};
Now all you need to do is to call this function when the body is loaded like this
<body onload="init();"> ... </body>
problem:
The problem with this solution, is that if you have a link that contains an anchor like this href="#" it will change the parent window to the child window To solve this problem, you have to use the third solution
Third solution:
This solution is also client-side and you have to use javascript. It is like the second solution except that you have to test if the link is a url to an external page or to an anchor before you redirect. so you need to define a function that returns true if it's a link to an external page and false if it's a simple anchor, and then you'll have to use this function like this
function init ()
{
TagNames = document.getElementById('iframe').contentWindow.document.getElementsByTagName('a');
for( var x=0; x < TagNames.length; x++ )
TagNames[x].onclick = function()
{
if ( is_external_url( this.href ) )
document.location = this.href;
}
};
and you also need to call this function when the body is loaded
<body onload="init();"> ... </body>
don't forget to define is_external_url()
update :
Here is the solution to get the url of the last child, it's just a simple function that looks from frames and iframes inside the paages and get the urls
function get_last_url($url)
{
$code = file_get_contents($url);
$start = strpos($code, '<frameset');
$end = strpos($code, '</frameset>');
if($start===false||$end===false)
{
$start = strpos($code, '<iframe');
$end = strpos($code, '</iframe>');
if($start===false||$end===false)
return $url;
}
$sub = substr($code, $start,$end-$start);
$sub = substr($sub, strpos($sub,'src="')+5);
$url = explode('"', $sub)[0];
return get_last_child($url);
}
$url = get_last_url("http://thetpgmusic.tk/");
header('Location: ' . $url);
exit();

Save the contents of manipulated div to a variable and pass to php file

I have tried to use AJAX, but nothing I come up with seems to work correctly. I am creating a menu editor. I echo part of a file using php and manipulate it using javascript/jquery/ajax (I found the code for that here: http://www.prodevtips.com/2010/03/07/jquery-drag-and-drop-to-sort-tree/). Now I need to get the edited contents of the div (which has an unordered list in it) I am echoing and save it to a variable so I can write it to the file again. I couldn't get that resource's code to work so I'm trying to come up with another solution.
If there is a code I can put into the $("#save").click(function(){ }); part of the javascript file, that would work, but the .post doesn't seem to want to work for me. If there is a way to initiate a php preg_match in an onclick, that would be the easiest.
Any help would be greatly appreciated.
The code to get the file contents.
<button id="save">Save</button>
<div id="printOut"></div>
<?php
$header = file_get_contents('../../../yardworks/content_pages/header.html');
preg_match('/<div id="nav">(.*?)<\/div>/si', $header, $list);
$tree = $list[0];
echo $tree;
?>
The code to process the new div and send to php file.
$("#save").click(function(){
$.post('edit-menu-process.php',
{tree: $('#nav').html()},
function(data){$("#printOut").html(data);}
);
});
Everything is working EXCEPT something about my encoding of the passed data is making it not read as html and just plaintext. How do I turn this back into html?
EDIT: I was able to get this to work correctly. I'll make an attempt to switch this over to DOMDocument.
$path = '../../../yardworks/content_pages/header.html';
$menu = htmlentities(stripslashes(utf8_encode($_POST['tree'])), ENT_QUOTES);
$menu = str_replace("<", "<", $menu);
$menu = str_replace(">", ">", $menu);
$divmenu = '<div id="nav">'.$menu.'</div>';
/* Search for div contents in $menu and save to variable */
preg_match('/<div id="nav">(.*?)<\/div>/si', $divmenu, $newmenu);
$savemenu = $newmenu[0];
/* Get file contents */
$header = file_get_contents($path);
/* Find placeholder div in user content and insert slider contents */
$final = preg_replace('/<div id="nav">(.*?)<\/div>/si', $savemenu, $header);
/* Save content to original file */
file_put_contents($path, $final);
?>
Menu has been saved.
To post the contents of a div with ajax:
$.post('/path/to/php', {
my_html: $('#my_div').html()
}, function(data) {
console.log(data);
});
If that's not what you need, then please post some code with your question. It is very vague.
Also, you mention preg_match and html in the same question. I see where this is going and I don't like it. You can't parse [X]HTML with regex. Use a parser instead. Like this: http://php.net/manual/en/class.domdocument.php

How to open a link which was parsed in a div?

My site parses a spanish dictionary and lets you search for more than one word at a time. If you look up "hola" you get the first div). Some words come up with suggestions, like "casa", instead of definitions like "hola":
And what i am looking for is this:
So, i would like to: when you click on the suggestions (like CASAR in the example I posted) to print the result in a div like HOLA. Here is the code used:
$words = array('word0','word-1');
function url_decode($string){
return urldecode(utf8_decode($string));
}
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
$cssReplace = <<<EOT
<style type="text/css">
// I changed the style
</style>
</head>
EOT;
$resultIndex = 0;
foreach($words as $word) {
if(!isset($_REQUEST[$word]))
continue;
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/search', $contents);
echo "<div style='
//style
", (++$resultIndex) ,"'>", $contents,
"</div>";
}
I have tried with: $contents .= '' . $word . '<br/>'; But it didn't work nor I know really where/how to use it.
Okay, I'll use jQuery for the example because it will be the easiest to get the job done specially if you are new to programming.
NOTE: I DO NOT RECOMMEND USING JQUERY -BEFORE- LEARNING JAVASCRIPT -- DO IT AT YOUR OWN RISK, BUT AT LEAST COME BACK AND LEARN JAVASCRIPT LATER
First, read up on how to download and install jquery here.
Secondly, you will want something a little like this, let's pretend this is your markup.
<div id="wrapper">
<!-- This output div will contain the output of whatever the MAIN
word being displayed is, this is where HOLA would be from your first example -->
<div id="output">
</div>
<!-- This is your suggestions box, assuming all anchor tags in here will result in
a new word being displayed in output -->
<div id="suggestions">
</div>
</div>
<!-- Le javascript -->
<script>
// Standard jQuery stuff, read about it on the jquery documentation
$(function() {
// The below line is a selector, it will select any anchor tag inside the div with 'suggestions' as identifier
$('#suggestions a').click(function(e) {
// First, stop the link going anywhere
e.preventDefault();
// Secondly, we want to replace the content from output with new content, we will use AJAX here
// which you should also read about, basically we set a php page, and send a request to it
// and display the result without refreshing your page
$.ajax({
url: 'phppage.php',
data: { word: 'casar' },
success: function(output) {
// This code here will replace the contents of the output div with the output we brought back from your php page
$('#output').html(output);
}
})
});
})
</script>
Hopefully the comments will shed some light, you need to then set up your php script which will be sent a GET request. (for example, http://some.address.com/phppage.php/?word=casar)
Then you just echo out the output from PHP
<?php
$word = $_GET['word'];
// Connect to some database, get the definitions, and store the results
$result = someDatabaseFunctionThatDoesSomething($word);
echo $result;
?>
Hope this helps, I expect you have a lot of reading to do!

PHP javascript call with PHP variable

Good day, I am having a very odd error with my PHP code. I am attempting to dynamically change the content of my webpage by reading from an xml file. I read in some data and assign the data to a PHP variable called $course_title and then attempt to call some Javascript that will update the "innerHTML" of a DOM element. Note: on the line "echo $course_title;' that prints out the correct data to the screen.
$fn = dirname(__FILE__)."/course.xml";
$xml = simplexml_load_file($fn);
$course_bookimagelocation = "";
foreach ($xml->children() as $child)
{
if($child[0]->getName()=="book")
$course_bookimagelocation = $child;
if($child[0]->getName()=="title")
$course_title = $child;
}
//Problems start here...
echo $course_title;
echo '<script type="text/javascript">document.getElementById("heading").innerHTML = "';
echo $course_title;
echo '";</script>';
What is very unique is that the first echo statement prints the correct information, but the next three lines, the .innerHTML does not get changed to that same value. Does anyone know what that is? What is also weird is that if I replace the second "echo '$course_title';" with something like 'Hello world!' then "Hello World!" appears as the innerHTML of the "heading" id object.
EDIT
In the XML file called course.xml, the title element is IC 210 Fall 2010 and the contents of $course_title is IC 210 Fall 2010 so the parsing of the php file appears to be correct and there does not seam to be any special characters like a " or '
I also tried putting everything on the same line and not luck... (I even made sure in the xml file that the <title> element had the text on the same line...
Make sure that .innerHTML = "Some text" are on the same line because .innerHTML = "\nSome Text\n" won't work in javascript.
If you want to have something like this:
.innerHTML = "
Some String
";
try:
.innerHTML = ""+
"Some String" +
"";
"call some Javascript that will update the "innerHTML" of a DOM element." for that we use AJAX, no?
well you can do that way but i think it would be simpler to have the text preloaded in some hidden DIV's and use your functions just to change content's of the DIVS or even toggle visibility of the DIV (as you prefer). That way you will avoid many escaping problem's referred in the comments.
that's the way i would do it if not to use AJAX

Categories