从PHP中获取HTML对象的价值

问题描述 投票:1回答:1

我有一个html对象:

<a href="https://website/" class="td-post-category" value="News" >News</a>

我从键入$this->get_category()得到的;用PHP。

我的问题是,是否有可能从PHP内部的HTML对象中获取值字段(新闻)。像$this->get_category().value$this->get_category()->value之类的东西。就像我们可以在Javascript中一样。

或者,如果您知道如何从函数中“提取”变量。就像我在$selected_category_obj_name中有一个名为function get_category()的变量一样,当我编写$this->get_category()时如何获得这个值,我怎样才能获得变量$selected_category_obj_name

我是PHP的新手,因此非常感谢一些指导。

php html wordpress
1个回答
1
投票

您可以使用preg_match()的正则表达式:

$html = '<a href="https://website/" class="td-post-category" value="News" >News</a>';
preg_match("/value=\"(.+)\"/i", $html, $matches);
var_dump($matches[1]); // News

该模式只是在value=""之间寻找任何不止一次的东西,将结果返回到$matches数组中。

或者DOMDocument并遍历DOM以获取元素的属性:

$html = '<a href="https://website/" class="td-post-category" value="News" >News</a>';
$doc = new DOMDocument;
$doc->loadHTML($html);
var_dump($doc->getElementsByTagName("a")->item(0)->getAttribute("value")); // News

Demos

© www.soinside.com 2019 - 2024. All rights reserved.