0

Let's say I have a "test.html" file with some example content:

<table>
 <tr>
  <td>'Test'</td>
  <td>Test "2"</td>
 </tr>
</table>

And I want to use that as a jQuery object. My first instinct would be to attempt:

var $testobject = $("<?php include('./test.html');?>");

But with the line breaks and quotes in test.html, this would fail. I specifically need the test.html file to be a jQuery object so it is hidden on load and is put in different places on the page with various triggered scripts, and I would prefer to use the more static PHP approach than a jQuery load. There must be a simple trick to manage this...

3
  • Try use file_get_contents instead include. Commented Feb 25, 2012 at 14:51
  • You could simply load the object into a variable using the jQuery ajax load function Commented Feb 25, 2012 at 14:51
  • 1
    I specifically don't want to use the jQuery load. Commented Feb 25, 2012 at 14:52

3 Answers 3

4

Read the static file using file_get_contents, and deal with special characters using json_encode:

var $testobject = $(<?php echo json_encode(file_get_contents('./test.html'));?>);

For example, if test.html contains:

<a href="/">
  Test
</a>

Then the output will be:

var $testobject = $("<a href=\"\/\">\n  Test\n<\/a>\n");
Sign up to request clarification or add additional context in comments.

6 Comments

Using my example test.html, this fails with this test.php file (nothing appears): <html><body> <script> var $testthing = <?php echo json_encode(file_get_contents('./test.html'));?>; $testthing.appendTo(document.body); </script> </body></html>
I should add that the PHP echo succeeds, the HTML appears as you describe it. But it doesn't display from appending to the document body...
@user You're missing the jQuery wrapper. $( <?php ... ?> );.
Oops, added jQuery wrapper and still nothing: var $testthing = $(<?php echo json_encode(file_get_contents('./test.html'));?>);
@user173342 You did never load the jQuery library.. See pastebin.com/jEpKRqq1 for the corrected version. (PHP: pastebin.com/RjN7H8sP).
|
0

use load :

create a div

$('#test').load('test.html');

var testObject = $('#div').find('table');

Comments

0

use output buffering:

<?php
ob_start();
include('./test.html');
$data = ob_get_contents();
ob_end_clean();
?>

var $testobject = $("<?=$data;?>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.