从php处理HTML [英] Manipulate HTML from php

查看:101
本文介绍了从php处理HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html文件, index.php 我想在< div> 与该文件的类 main 替换为另一个文本。如何实现?

I'm having an html file, index.php I want to take the content within a <div> with the class main of that file and replace it with another text. How can i achieve that?

html中的示例内容:

Sample content in html:

<div class="main">
Replace this text with some code!
</div>

我想使用php获取此div内的内容,并将其替换为其他内容。但我不知道如何做到这一点。

I want get the content within this div using php and replace it with another content. But I have no idea on how to do this.

更新:
我知道客户端技巧与javascript。我想做这个服务器端。而文件将是html而不是php。所以我想我必须打开php中的html,尽管我不是精确的如何。

Update: I'm aware of client side trick with javascript. I want to do this server side. And the file will be html and not php. so I think i have to open the html in php and do this, though i don't precisely how.

可以使用xpath或html dom解析器或某事?谷歌搜索给了我这些条款,但我不知道他们实际是什么。

Can this be done with xpath or html dom parser or something? A google search gave me these terms but i have no clue what they actually are.

推荐答案

你可以使用PHP的 DOM 类/函数来做到这一点。

You can use PHP's DOM classes/functions to do this.

首先创建/加载您的文档:

Start by creating/loading your document:

$d = new DOMDocument();
$d->loadHTML($yourWellFormedHTMLString);

然后,您需要找到要更改的文档节点。您可以使用XPath执行此操作:

Then you'll want to locate the document node that you want to alter. You can do this using XPath:

$xpathsearch = new DOMXPath($d);
$nodes = $xpathsearch->query('//div[contains(@class,'main')]');  

然后,您将需要遍历匹配的节点,并在其中创建新节点:

Then you'll want to iterate over matching nodes, and create new nodes inside:

foreach($nodes as $node) {
    $newnode = $d->createDocumentFragment();
    $newnode->appendXML($yourCodeYouWantToFillIn);
    $node->appendChild($newnode);
}

如果你不介意在早期阶段搞乱图书馆开发,请查看 CAST (内容编址样式模板)。它的设计很适合你所描述的内容,如果没有其他的,你可以在源代码中查看示例。

If you don't mind messing around with a library at an early stage of development, take a look at CAST (content-addressed style templating). It's pretty much designed to do what you're describing, and if nothing else, you could peer inside the source to see examples.

(注意:我确定精明的将会注意到 // div [contains(@ class,'main')] 不是恰好相当于CSS选择器 div.main ...因为类属性可以包含多个类。这样做正确我认为最好从简化的表达式开始,当你介绍人们,即使最好的那些谁去这条路线,最终了解xpath好足以处理这个权利,或者,只需使用ids更多而不是类。:)

(NOTE: I'm sure the astute will note that //div[contains(@class,'main')] isn't exactly the equivalent of the CSS selector div.main ... since the class attribute can contain more than one class. Doing this precisely is unwieldy enough I think it's better to start with the simplified expression when you're introducing people to it, even if it might best for those who go this route to eventually get to know xpath well enough to handle this right. Or, just use ids more instead of classes. :)

这篇关于从php处理HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆