Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a div's content from a Static HTML file using PHP or jQuery or Ajax?

Hello friends a newbie question...

The Issue is like this:

I have a static HTML file and I want to import just a portion of that file into another page. How can I do that.

Example Code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Some title here</title>

<link rel="stylesheet" type="text/css" href="styles.css" />

</head>

<body>

<div id="box-1">
    <div class="block">

    <!-- Some code here -->

    </div>
</div>

<div id="box-2">
    <div class="block">

    <!-- Some code here -->

    </div>
</div>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>

Now what I want is to read this HTML file and import just this bit:

<div id="box-1">
    <div class="block">

    <!-- Some code here -->

    </div>
</div>

Is there a way of doing it?

Kindly help.

Even a PHP, jQuery, Ajax or any other solution will also do. Please help me.

like image 787
Vikram Rao Avatar asked Dec 13 '22 17:12

Vikram Rao


2 Answers

You can use jQuery's load() to specify only a certain container to be loaded:

$('#targetdiv').load('static.html #box-1');
like image 67
Pekka Avatar answered May 02 '23 12:05

Pekka


Here's a solution that differs from the others: It performs a one-time import of a section of content from a large number of static html files/pages (in case that was what you were wanting). I used it successfully to import about 700 pages from straight html to a cms database.

// get the pages you want to import
$pages = array('page1.html', 
    'page2.html',
    'page3.html'
);

foreach($pages as $p) {
    $url = 'http://yourDomain.com/' . $p;

    // load the webpage
$file = file_get_contents($url);

if($file) {

    list($before,$content) = explode('<body>',$file); // chop off beginning
    unset($before);
    list($content) = explode('<div id="box-2">',$content); // chop off end;

            $resultArray[] = trim($content);

            // or do it this way to keep the filename associated with the content
            // $resultArray[$p] = $content;

}//if file

} //endforeach;

// $resultArray holds your stripped content
// do something with $resultArray;
like image 44
JakeParis Avatar answered May 02 '23 11:05

JakeParis