简体   繁体   中英

Load divs' content from another domain to my pages' php variable

I'm trying to figure it out how to take information from another site(with different domain name) and place it in my php program. Explanation: User inputs URL from another site. jQuery or PHP takes information from entered URL. I know where the information is (i know its' divs ID) And that var is put into my php program as a variable $kaina, for example.

EX: User enters URL: http://www.sportsdirect.com/lee-cooper-bud-mens-boots-118358 And I want to get the Price. (27,99)

What lang should I use? PHP? or jquery? or anything else? What function should I use? How should the program look like?

Thank you for your answers :)

I'd say you have to use php (curl or file_get_contents) to download the page on to your server, parse it or use regular expression to get the price. But in this case it will be even trickier because it looks like this link leads to a page that uses javascript.

But you have to know the format of how you are going to extract the data. So PHP will do the job.

PHP's cURL library should do the trick for you: http://php.net/manual/en/book.curl.php

<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

You need to research on each of the step mentioned below,

One Thing That you can do is, post the message entered by the user to the server means PHP file, there you can extract the url entered by the user, In order to extract the URL from the user post, you can use regex search:- Check this link out:- Extract URLs from text in PHP

Know you can curl to the url extracted from the user input.

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_URL, $extracted_url ); 
$html = curl_exec ( $ch ); 
curl_close($ch);

The curl output will contain the complete html of the page, you can then use a HTML parser

$DOM = new DOMDocument;
$DOM->loadHTML($str);

to parse till the required div is found, to have its value.

I would proabaly do something like this:

  1. get the contents of the file: $contents = file_get_contents("http://www.sportsdirect.com/lee-cooper-bud-mens-boots-118358")
  2. convert the contents you just got to xml: $xml = new SimpleXMLElement($contents);
  3. search the xml for the node with attribute itemprop="price" using xpath query
  4. read the contents of that node, et voila, you have your price

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM