0

Let's say you wanted to parse the DOM with PHP. You can easily achieve this using the DomDocument.

However, in order to do so, you would need to load some HTML using loadHTML or loadHTMLFile and provide the functions with a string containing HTML (or a file path in the case of loadHTMLFile).

As an example, if you just wanted to get an element with a specific ID (in PHP, not JavaScript), WITHIN your page, what can you do?

4
  • 1
    PHP is server side and element is in UI side i think you need JS to pass the ID to PHP from the UI Commented Feb 5, 2019 at 23:58
  • 2
    @AndréFilipe Please do not suggest edits which only add italics to words. These changes are not useful. Commented Feb 5, 2019 at 23:59
  • 1
    @duskwuff it should have been rejected question is who approved :) Commented Feb 6, 2019 at 0:01
  • Does the DOMDocument, or any other tool within PHP have the capability of parsing local DOM elements? Commented Feb 6, 2019 at 0:02

2 Answers 2

2

If you have PHP code generating the page, you could use the output buffer to generate the page in memory, edit the generated page and then flush it to the browser. You can only change the DOM before the browser gets it.

You could do the following:

ob_start(); // Should be called before any output is generated

// ... PHP code that outputs HTML ...

$generated_html = ob_get_clean(); // Store generated HTML to string

// Load and manipulate HTML
$doc = new DOMDocument();
$doc->loadHTML($generated_html);

// ... Manipulate the generated HTML ...

echo $doc->saveHTML(); // echo the modified HTML

However, since you are generating the HTML it would make more sense to change whatever you need to change before it's generated to reduce procesing time.

If you want to change the HTML of a page which is already shown in the browser you'll need another way (such as JS/AJAX) since at that point PHP can't possibly access the DOM.

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

Comments

0

getElementById method can be invoked on the DOMDocument instance with id string to get the element. 1

$element = $testDOMDocument->getElementById('test-id');

1 Comment

This is invalid PHP syntax. In PHP, you use -> to access object properties, not .

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.