Getting HTML element in PHP - javascript

I am struck in a problem, i want a small amount of data from a site, but this data is present in different pages.
Hence i used curl request to call this pages
Problem:
curl request gives my a html page, and finding that small amount of content is difficult with php as,
It is very simple to move through the HTML Dom with JavaScript(jquery). Can i move with same ease with php in HTML Dom
any help would be appreciated , please provide me link of such site also
I am not asking for all the coding , but just a library or link will do
if there is any trick it will also do , a small example like fetching element with ID would be of great help
Thanks

Yes you can. You can use DomDocument and DomXPath to navigate your HTML tree and search it.
$doc = new DOMDocument();
$doc->loadHTML($yourHtml); // HTML as string, use loadHTMLFile() to load a file.
$xpath = new DOMXpath($doc);
$elements = $xpath->query("*/div[#id='yourTagIdHere']");
if (empty($elements) || $elements->length == 0)
echo "Not found";
else
{
// $elements now contains a DOMNodeList of matching elements
// which you can foreach() through.
}

Related

Using jQuery to manipulate a composed HTML page?

I am working on a data scraping application. The pages I want to scrape have already been collected by server-to-server requests, and are currently stored in my database. I use an axios request to retrieve them from my database, and I now want to traverse/manipulate the pages using my VueJS application.
Here's what I have so far...
import $ from 'jquery'
...
...
axios.get('/mydomain/fetch_page/1')
.then(function (response) {
console.log(response.data.body); // log point #1
let $page = $(response.data.body);
// let $heading = $page('h2');
console.log($page); // log point #2
})
At log point #1 the page looks fine. It includes the entire page: DOCTYPE, html, head, body, etc
At log point #2, it is an object where each property represents a DOM node, including text nodes.
If I un-comment the line that queries the $page for a $heading, I get an error telling me that $page is not a function. What am I doing wrong?
$page is a jQuery object, not a function. Just as when you're writing web applications using jQuery, you call methods on it, you don't call it as a function.
To get the h2 elements, use the .find() method:
let $heading = $page.find("h2");

Using PHP in a Javascript music player playlist

I've been working on a music player that's quite simple and to add music to it you would have to upload it to Dropbox and then manually edit the file (in this case index.php) where the playlist is held.The player then plays the links.
But what I've done is made a file which inserts value through mysql into the database.Two columns:
songname, url
Index.php:
`$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_N",
cssSelectorAncestor: "#jp_container_N"
}, [
{
title:"C O O L",
artist:"Le Youth",
mp3:"this is where the link must sit",
},`
How can I implement PHP query that selects the name and the link from database into that part of javascript code?
I'm sorry if there's some unclear things for you, please ask I will try to make everything clear.
PHP is a server-side language and it dies after it renders the page. So, you have two good options here.
First one is to grab all the links/names from the database, and then echo that into a JS object (using JSON seems the easiest way to handle the conversion), and then just call the link you need from that JS object. You can build the whole title/artist/mp3 object using PHP and be good to go. It should look something like this:
var mySonglist = <?php echo json_encode($databaseData) ?>;
The other option would require making AJAX calls to retrieve the link of the selected mp3. Although this might seem closer to what you're asking, due to its speed (it makes another server call), I'd suggest you do it only if you have a really, really huge number of songs at once.
So, the bottom line is: extend your PHP functionality to grab everything you need from the database, all the data, and then put that data into a JS variable which you will use to configure your player.
I am not sure that you can do db queries inside your script functions, But Do the queries outside the function and pass the php variables as arguments for the function. Below is an example.
<?php
$var="Select query here";
$name=$var[0]; $url = $var[1];
?>
<script>
play('$name','$url');
function play(name,url);
{
//your code goes here..
}
</script>

Grab GET ajax calls from page just by providing URL

Here's an example of a page from the API I'm working with:
http://www.easports.com/fifa/football-club/apps/proclubs/PS4/CHIP%20IT%20BRO
On this page almost all of the data is being loaded in via GET calls.
Here are 3 of the main calls that I'm interested in:
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/members
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/info
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/stats
You'll notice that there is one thing in common with these calls, and that is the number after the "clubs/" part of the URL. In this case, it's 66232. That is the ID of the club. Basically, if I have this ID, I can get all of the information I need from this API.
The problem:
The only way I can grab this ID is if I manually inspect the page myself via Firebug. On my website, users will need to be able to automatically register their clubs. I want them to be able to provide the URL to their club page, eg.:
http://www.easports.com/fifa/football-club/apps/proclubs/PS4/CHIP%20IT%20BRO
Is there any way I can grab the ID in these ajax calls just by having the URL of the page? I don't even need the info that is returned from these calls, I just need the club ID that is part of the URL of these calls, eg.:
www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/66232/members
I can just use some string functions to grab the ID after the "clubs/" substring up until the next "/".
I've been looking all over for a solution but can't seem to find what I'm looking for.
Thanks in advance. :)
EDIT:
Why is my question getting downvoted like crazy? I think I explained it pretty well. :/
Try using PHP's DOMDocument:
// clubId.php
<?php
$dom = new DOMDocument; #$dom->loadHTMLFile('http://www.easports.com/fifa/football-club/apps/proclubs/PS4/CHIP IT BRO');
$bod = $dom->getElementsByTagName('body');
if($bod = $bod->item(0)){
$cid = $bod->getAttribute('club-id');
$ea = 'http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/'.$cid;
$members = #file_get_contents("$ea/memebers");
$info = #file_get_contents("$ea/info");
$stats = #file_get_contents("$ea/stats");
}
else{
echo 'Sorry, the Page is Probably Blocked!';
}
?>
Now you can echo $members, and the like, into HTML that creates JavaScript. Of course, you should have a firm grasp on JavaScript Objects and Arrays.
IT DOES APPEAR BLOCKED THOUGH!!!

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

parse XML and insert data in MySQL table

I am trying to parse a xml file that i have (using javascript DOM). and then i want to insert this data in a mysql table (using php).
I know how to parse xml data. But i am unable to figure out how to use php and javascript together and insert data in mysql table.
Kindly help me in this.
Best
Zeeshan
Why don't you just use PHP DOM to parse the XML ?
e.g:
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
After loaded your document $doc you can use the PHP DOM functions.
The JavaScript needs to send the data to the server. There are several ways this can be achieved.
Generate a form and submit it
Use XMLHttpRequest directly
Use a library like YUI or jQuery
Once there, you get the data (from $_POST for example) and insert it into MySQL as normal.
You can use jQuery to do this, for example:
<house>
<roof>as</roof>
<door>asd</door><window number="12">iles</window></house>
$('path_to_xml',xml).each(function(){
roof = $('roof',this).text();
door = $('door',this).text();
num_wind = $('window',this).attr('number');
});

Categories