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
DOMDocumentis possibly the ideal (native) tool for this task, but you’ll probably want to look into theDOMDocument::loadHTML()method instead of theloadHTMLfile()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:I am using
preg_replace(), but you shouldn’t have any problems adapting it to useDOMDocumentnodes. It’s also worth noticing that theob_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
DOMDocumentexample: