marasva
marasva

Reputation: 53

Getting value from HTML object in PHP

I have an html object:

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

Which I get from typing $this->get_category(); in PHP.

My question here is if it is possible to get the value-field(News) from the HTML-object inside of PHP. Something like $this->get_category().value or $this->get_category()->value. Like we could in Javascript.

Or if you know how to "extract" variables from functions. Like if I had a variable named $selected_category_obj_name in the function get_category(), how to get this value when I have written $this->get_category(), how can I get the variable $selected_category_obj_name?

I am new to PHP, so some guiding would be very appreciated.

Upvotes: 1

Views: 1586

Answers (1)

ishegg
ishegg

Reputation: 9937

You can use a regular expression with 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

The pattern simply looks for anything more than once in between value=" and ", returning the results into the $matches array..

Or DOMDocument and traverse the DOM to get to the attribute of the element:

$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

Upvotes: 1

Related Questions