在 PHP 变量或类似方式上使用 html 代码(字符串)选择器搜索


use selector search on html code(string) on PHP variable or ways alike

im 目前所做的是我有一个文本区域供用户复制和粘贴 html 代码。我想获取该 HTML 文件的某个元素。在纯HTML中,这可以通过jQuery选择器完成。但我认为当 HTML 代码位于变量上并被视为字符串时,这是完全不同的事情。如何以这种方式获取某个元素位置?

代码是:

        function searchHtml() {
            $html = $_POST; // text area input contains html code
            $selector = "#rso > div > div > div:nth-child(1) > div > h3 > a"; //example - the a element with hello world
            $getValue = getValueBySelector($selector);  //will return hello world     
        }
        function getValueBySelector($selector) {
            //what will i do here?
        }
        searchHtml();
你可以

看看SimpleHTMLDom Parser(手动 http://simplehtmldom.sourceforge.net/manual.htm)。这是一个强大的工具,用于解析HTML代码以查找和提取各种元素及其属性。

对于您的特定情况,您可以使用

// Create a DOM object from the input string
$htmlDom = str_get_html($html);
// Find the required element
$e = $htmlDom->find($selector);

哦,你必须将提供的输入值传递给getValueBySelector()函数:-)