Flynn
Flynn

Reputation: 6181

PHP Modify an included file

I have a bunch of .html files that I am including on a page. Conditionally, I need to add classes to some of the components in these files, for example:

<div id='foo' class='bar'></div>

to

<div id='foo' class='bar bar2'></div>

I know I can do this with some inline PHP like this

<div id='foo' class="bar <?php echo " bar2"; ?>"></div>

However, having PHP in any of the files I'm including is not an option.

I also looked into including a file and then modifying afterward, but that doesn't seem possible. Then I was thinking I should read the files line-by-line, and add it in then.

Is there a nicer way I'm not thinking of?

Upvotes: 0

Views: 297

Answers (4)

Amal Murali
Amal Murali

Reputation: 76646

Since having PHP is not an option, you could use PHP's DOM Parser with an XPath selector:

$dom = new DOMDocument();
$dom->loadHTMLFile($htmlFile);
$finder = new DomXPath($dom);

// getting the class name using XPath
$nodes = $finder->query("//*[contains(@class, 'bar')]");

// changing the class name using setAttribute
foreach ($nodes as $node) {
    $node->setAttribute('class', 'barbar2');
}

// modified HTML source
$html = $dom->saveHTML();

That should get you started.

Upvotes: 2

ErnestV
ErnestV

Reputation: 137

Depends on what you actually want to achieve - but basically this tends to be better solved by jQuery on the client.

But anyway you might put your HTML fragments in a DOM object, analyze and modify it, and read the HTML back after the modifications, for example:

// including an HTML file writes to the output stream, so buffer this
ob_start();
include('myfile.html');
$html = ob_get_clean();

// make a DOMDocument
$doc = new DOMDocument();
$doc->loadHTML($html);

// make the changes you need to
$xpath = new DOMXPath($doc);
$nodelist $xpath->query('//div[@id="foo"]');
// etc...

// get modified HTML
$html = $doc->saveHTML();

Hope this helps.

Upvotes: 0

itsazzad
itsazzad

Reputation: 7277

You may need to use .php instead of .html. So do like below:

$variableClass="bar2";
include("htmlfilename.html");

where the htmlfile.html consists of

<div id='foo' class="bar <?php echo $variableClass; ?>"></div>

Upvotes: 0

apparatix
apparatix

Reputation: 1512

You can use the DOMDocument class in PHP to retreive the information from the file and then add attributes and data.

I don't really remember the code for DOMDocument so I haven't included any code here (sorry), but here are some links:

Use this method to get the HTML from your file:

http://php.net/manual/en/domdocument.loadhtmlfile.php

Review the DOMDocument class:

http://php.net/manual/en/class.domdocument.php

Upvotes: 1

Related Questions