1

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.

6
  • 1
    Question. Why would you want to do that? Commented Feb 16, 2018 at 14:46
  • 1
    Is this within WordPress? Commented Feb 16, 2018 at 14:47
  • @Adam can it be Wordpress? Doesn't get_category() return an array or an object? Commented Feb 16, 2018 at 14:56
  • HTML doesn't have objects, it does have <object>, The attribute value is invalid for <a>. Looks like you're also new to HTML. Commented Feb 16, 2018 at 14:57
  • @ishegg - Not entirely sure without referring to the WordPress Codex, but if it is WP, it'll make debugging this weird use case a bit easier possibily. Commented Feb 16, 2018 at 14:58

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.