开发者

PHP Search and Replace on page

I am trying to find a way to search through a 开发者_运维问答page in php to replace the names of form elements.

I guess I should explain. I'm doing a job for a friend and I want to make an easy database updater that is robust and can withstand adding elements without the person knowing much about php or databases.

In short, I want to search through a form and replace all the name="%name%" with the respective database table key names, so I can use a simple foreach method to update the table.

So I was looking at the DOMDocument element to open an html page and replace every form name inside in order with the corresponding table keys, but I wasn't sure if I can open a php page with loadHTMLfile or not. And, if I could open up a php page, would opening itself cause an infinite loop? Or would it just parse the html as if it were looking at client-side html?

Is there any way to do what I want? If not, that's OK, I'll just make it a little less awesome, but I was just wondering.


It's perfectly doable.

The DOMDocument is possibly the ideal (native) tool for this task, but you'll probably want to look into the DOMDocument::loadHTML() method instead of the loadHTMLfile() one.

To get the processed PHP page into a string, you can request the page with CURL, file_get_contents() or a similar alternative. This involves making an additional request and adding specific control logic to avoid an endless loop.

A better alternative might be to use output buffering, here is a simple example I have at hand in how to replace the contents of the <title> tag:

<?php

ob_start();

echo '<title>Original Title</title>';

/*    get and delete current buffer      &&  start a new buffer */
if ((($html = ob_get_clean()) !== false) && (ob_start() === true))
{
    echo preg_replace('~<title>([^<]*)</title>~i', '<title>NEW TITLE</title>', $html, 1);
}

?>

I am using preg_replace(), but you shouldn't have any problems adapting it to use DOMDocument nodes. It's also worth noticing that the ob_start() call must be present before any headers / contents are sent to the browser, this includes session cookies and so on.

This should get you going, let me know if you need any more help.


A generic DOMDocument example:

<?php

ob_start(); // This must be the very first thing.

echo '<html>'; // Start of HTML.
echo '...'; // Your inputs and so on.
echo '</html>'; // End of HTML.

// Final processing, the $html variable will hold all output so far.
if ((($html = ob_get_clean()) !== false) && (ob_start() === true))
{
    $dom = new DOMDocument();

    $dom->loadHTML($html); // load the output HTML

    /* your specific search and replace logic goes here */

    echo $doc->saveHTML(); // output the replaced HTML
}

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜