2014-12-19 40 views
-2

我刚刚开始学习PHP,我无法弄清楚如何从HTML元素中获取文本。如何获取PHP中的HTML元素中的文本?

这里是我的HTML代码(我做网页的文本编辑器):

<div id="example-one" contenteditable="true"> 
    <style scoped> 
     #example-one { margin-bottom: 10px; } 
     [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; } 
    [ contenteditable="true"]:hover { outline: 2px dashed #0090D2; } 
</style> 
<p>Everything contained within this div is editable in a browser that supports <code>HTML5</code>. Go on, give it a try: click it and start typing.</p> 
</div> 

你们可以请说明我会得到段落元素的文字,或者div元素?

感谢收听! -Sam

回答

1

如果我正确理解您的问题,您正在尝试获取HTML元素中的文本值并在PHP中使用它。

这并没有什么意义,因为PHP是服务器端语言,HTML是客户端将会看到的东西。实际上这非常好,因为它允许您在PHP中生成HTML,将PHP与HTML分开以获得您想要的内容。

例子:

<form method="post" action""> 
    <input name="someInputThatsAlwaysHere" /> 
    <?php 
    //Now this is PHP, so we can have some fun, like having control statements: 
    if($condition === true) { 
    ?> 
    <input name="isOnlyHereIfConditionIsTrue" /> 
    <?php } else { ?> 
    <input name="isOnlyHereifConditionIsFalse" /> 
    <?php } ?> 
</form> 
0

这是标记向上传递到服务器?如果是这样的话,那么这样做的例子可能有助于找到here,如果你对正则表达式感到满意的话。否则,您可以使用字符串的方式并使用PHP API中的字符串拆分来获取内部内容。

如果你在客户端,你将不会使用PHP,而是使用JavaScript。

var content = $("#example-one").html(); 
0

一个方法:

<?php echo'<div id="example-one" contenteditable="true"> 
    <style scoped> 
     #example-one { margin-bottom: 10px; }  
     [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; } 
     [ contenteditable="true"]:hover { outline: 2px dashed #0090D2; } 
    </style> 
    <p>Everything contained within this div is editable in a browser that supports<code>HTML5</code>. Go on, give it a try: click it and start typing.</p> 
    </div>'; 
?> 

另一种方法:

<?php 

$html = '<div id="example-one" contenteditable="true"> 
    <style scoped> 
     #example-one { margin-bottom: 10px; } 
     [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; } 
     [ contenteditable="true"]:hover { outline: 2px dashed #0090D2; } 
    </style> 
    <p>Everything contained within this div is editable in a browser that supports <code>HTML5</code>. Go on, give it a try: click it and start typing.</p> 
    </div>'; 
$content = getTextBetweenTags('html', $html, 1); 
foreach($content as $item) 
{ 
    echo $item.'<br />'; 
} 

?> 
如果你使用jQuery,你可以通过做一些像访问股利或段落标记的id