PHP 页面搜索和替换
我正在尝试找到一种在 php 中搜索页面以替换表单元素名称的方法。
我想我应该解释一下。我正在为一位朋友做一份工作,我想制作一个简单的数据库更新程序,该更新程序功能强大,并且可以承受添加元素,而无需该人对 php 或数据库了解太多。
简而言之,我想搜索一个表单,并将所有 name="%name%" 替换为相应的数据库表键名称,这样我就可以使用简单的 foreach 方法来更新表。
所以我正在查看 DOMDocument 元素来打开一个 html 页面,并按顺序用相应的表键替换里面的每个表单名称,但我不确定是否可以使用 loadHTMLfile 打开一个 php 页面。而且,如果我可以打开一个 php 页面,打开它本身会导致无限循环吗?或者它会像查看客户端 html 一样解析 html 吗?
有什么办法可以做我想做的事吗?如果没有,那也没关系,我只是让它变得不那么精彩,但我只是想知道。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是完全可行的。
DOMDocument
可能是完成此任务的理想(本机)工具,但您可能需要查看DOMDocument::loadHTML()
方法而不是loadHTMLfile()
方法。要将处理后的 PHP 页面转换为字符串,您可以使用 CURL,
file_get_contents()
或类似的替代方案。这涉及发出额外的请求并添加特定的控制逻辑以避免无限循环。更好的选择可能是使用 输出缓冲,这里是我手头上有一个简单的例子,说明如何替换</code> 标记的内容:
我正在使用
preg_replace()
,但是您应该不会有任何适应问题它使用DOMDocument
节点。还值得注意的是,在将任何标头/内容发送到浏览器之前,必须存在ob_start()
调用,这包括会话 cookie 等。这应该可以帮助您继续前进,如果您需要更多帮助,请告诉我。
一个通用的 DOMDocument 示例:
It's perfectly doable.
The
DOMDocument
is 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 useDOMDocument
nodes. 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
DOMDocument
example: