用PHP检索textarea的值 [英] Retrieve value of a textarea with PHP

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

问题描述

也许有人会知道如何使用PHP获取HTML文档中特定元素的值吗?我现在正在做的是使用file_get_contents从另一个网站提取HTML代码,并且在该网站上有一个textarea:

Would anyone perhaps know how to get the value of a specific element in an HTML document with PHP? What I'm doing right now is using file_get_contents to pull up the HTML code from another website, and on that website there is a textarea:

<textarea id="body" name="body" rows="12" cols="75" tabindex="1">Hello World!</textarea>

我想做的是让我的脚本执行file_get_contents,然后拔出"Hello World!".来自文本区域.那可能吗?再次抱歉打扰你们,您会提供这样有用的建议:].

What I want to do is have my script do the file_get_contents and just pull out the "Hello World!" from the textarea. Is that possible? Sorry for bugging you guys, again, you give such helpful advice :].

推荐答案

不要因为打扰我们而感到抱歉,这是我很乐意回答的一个好问题.您可以使用 PHP简单HTML DOM解析器来获得所需的内容:

Don't be sorry for bugging us, this is a good question I'm happy to answer. You can use PHP Simple HTML DOM Parser to get what you need:

$html     = file_get_html('http://www.domain.com/');
$textarea = $html->find('textarea[id=body]'); 
$contents = $textarea->innertext;

echo $contents; // Outputs 'Hello World!'

如果要使用file_get_contents(),则可以这样做:

If you want to use file_get_contents(), you can do it like this:

$raw_html = file_get_contents('http://www.domain.com/');
$html     = str_get_html($raw_html);
...

尽管我认为不需要file_get_contents(),因为您可以使用outertext方法来获取原始的完整HTML,如果需要的话:

Although I don't see any need for the file_get_contents() as you can use the outertext method to get the original, full HTML out if you need it somewhere:

$html     = file_get_html('http://www.domain.com/');
$raw_html = $html->outertext;


只需踢一下,您还可以使用单线正则表达式来做到这一点:


Just for the kicks, you can do this also with an one-liner regular expression:

preg_match('~<textarea id="body".*?>(.*?)</textarea>~', file_get_contents('http://www.domain.com/'), $matches);
echo $matches[1][0]; // Outputs 'Hello World!'

我强烈建议您这样做,因为您更容易受到可能会破坏此正则表达式的代码更改的影响.

I'd strongly advise against this though as you are a lot more vulnerable to code changes which might break this regular expression.

这篇关于用PHP检索textarea的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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