Leverage the power of DOMXPath in combination with the query function

Here is a snippet of HTML code to work with:

<ul id="tree">
      <li>
        <a href="">first</a>
        <ul>
          <li><a href="">subfirst</a></li>
          <li><a href="">subsecond</a></li>
          <li><a href="">subthird</a></li>
        </ul>
      </li>
      <li>
        <a href="">second</a>
        <ul>
          <li><a href="">subfirst</a></li>
          <li><a href="">subsecond</a></li>
          <li><a href="">subthird</a></li>
        </ul>
      </li>
    </ul>
    

We need to parse this HTML code using DOMXPath::query() and foreach() in order to display the following structure:

- first
    -- subfirst
    -- subsecond
    -- subthird
    - second
    -- subfirst
    -- subsecond
    -- subthird
    

Below is a piece of code that can help achieve this:

$xpath = new \DOMXPath($html);
    $catgs = $xpath->query('//*[@id="tree"]/li/a');
    foreach ($catgs as $category) {
        // first level
        echo '- ' . mb_strtolower($category->nodeValue) . '<br>';
    
        // second level
        // code for second level here
    } 
    

Thank you in advance!

Answer ā„–1

Why DOMBLAZE was created:

/* DOMBLAZE */ $doc->registerNodeClass("DOMElement","DOMBLAZE"); class DOMBLAZE extends DOMElement{public function __invoke($expression) {return $this->xpath($expression);} function xpath($expression){$result=(new DOMXPath($this->ownerDocument))->evaluate($expression,$this);return($result instanceof DOMNodeList)?new IteratorIterator($result):$result;}}

$list = $doc->getElementById('tree');

foreach ($list('./li') as $item) {
    echo '- ', $item('string(./a)'), "\n";
    foreach ($item('./ul/li') as $subitem) {
        echo '-- ', $subitem('string(./a)'), "\n";
    }
}

Expected result of the code above:

- first
-- subfirst
-- subsecond
-- subthird
- second
-- subfirst
-- subsecond
-- subthird

DOMBLAZE is considered to be a budget-friendly alternative to FluentDOM.

Answer ā„–2

In order to tackle the second tier, you may also opt for an additional query:

$document = new DOMDocument();
$document->loadHTML($html);
$xpath = new DOMXpath($document);
$nodes = $xpath->query('//ul[@id="tree"]/li');
foreach($nodes as $node) {
    $header = $xpath->query('./a', $node)->item(0)->nodeValue;
    echo "- $header <br/>";
    foreach($xpath->query('./ul/li/a', $node) as $subNode) { // fetch data on the second level
        echo '-- ' . $subNode->nodeValue . '<br/>';
    }
}

check out the example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Maintaining the original layout upon refreshing the page

Incorporating two forms on my website, I added a button that transitions between the login and sign-up forms smoothly. The process is as follows: Initially, the login form is displayed; clicking the button switches to the sign-up form. Proceeding to subm ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...

Disable Button's Shadow when it is in an active state (clicked)

Check out the DEMO to see the button animation CSS in action. The CSS code for the button animations is as follows: .btnliner { /* CSS properties */ } /* More CSS properties */ .btnliner:hover { /* Hover effects */ } Here is the corresponding J ...

Having trouble retrieving all img tags while scraping a website using BeautifulSoup (BS4)?

My goal is to collect a list of all the <img> image tags from a website. Unfortunately, I'm only able to retrieve a few and not the rest even though they are present in the HTML code when I inspect with developer tools. In my code snippet below, ...

Is there an HTML editing tool that has the ability to collapse code blocks by tags and rearrange them?

I'm in search of a text editor or IDE that includes syntax highlighting and allows me to collapse HTML code blocks by tag. I currently use Eclipse, but its "folding" feature only works on top level tags like TABLE, not child tags like TD and TR. Are t ...

Switch up the position of an element every time the page is refreshed

I have a webpage containing 5 images, each measuring 48px by 48px. I would like these images to be displayed in random positions on the page every time it is loaded. While I am aware that I will need to use CSS and JavaScript for this task (specifically f ...

What defines 'user interaction' when it comes to preventing XSS attacks?

I have been researching how to protect my code from XSS attacks, and all the examples I've found focus on validating direct user input (like in a contact form or login). However, I'm unsure if I should still secure my code even if there is no wa ...

The Selenium code is encountering difficulty retrieving the text from an element

I'm attempting to retrieve the website owner using my local whois with the following code: link = "ebdicorp.com.br" service = service.Service('C:\Selenium\chromedriver.exe') service.start() capabilities = {'chrome.binary' ...

PHP Retrieve Current Time with AM/PM Display

Can anyone help me figure out how to use PHP to get the current time along with AM/PM indication? The code I have doesn't seem to be working correctly. Here is the code snippet that I am currently using: $format1 = date("G"); // this should give the ...

Tips for creating CSS styles for a selected input field

I seem to be stuck in a situation where my screen looks similar to the screenshot provided. There are four input elements that I would like to have bordered just like in the image, complete with a circled tick mark. I've managed to create these four i ...

Is there a way to develop a login form that retrieves information from a Google Sheet database?

Please help me with a solution. I have developed a registration form which effectively saves users' information in a Google Sheet. However, now I am yearning to create a login form that verifies the stored data and redirects the user to a different pa ...

Apache httpd exceeds memory usage resulting in server crashing

My server is running on an Intel(R) Xeon(R) CPU X3440 with 8GB of RAM. Currently, Apache seems to be consuming all the available RAM, causing the server to become unresponsive. This is my current Apache Configuration: <IfModule prefork.c> StartSe ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

Navigate through the overlay's content by scrolling

Objective: Looking to implement a scroll feature for long content. Issue: Not sure how to create a scroll that allows users to navigate through lengthy content. Thank you! function openNav() { document.getElementById("myNav").style.height = "1 ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what Iā€™m aiming for: If ...

Position icons and images on the right side, and the textarea on the left side of the page (using Twitter

Summary: Here is the desired end result shown in the image below. Alternatively, you can refer to the JSFiddle. Ideally, only CSS should be used without changing the DOM structure. The icons need to be aligned completely to the right using the .pull-right ...

Issue encountered with MySQL: Mysterious error when trying to initiate MySQL and Apache servers

Whenever I try to shutdown or restart my computer, WAMP fails to connect with MySQL across all versions of bitnami. I made sure to close Skype and even switched to XAMPP, but the issue persisted upon shutting down. Eventually, I went back to bitnami only t ...

The parent's height remains unaffected by the margins of its child element

My code snippet is concise: .parent{ box-sizing: border-box; } .child{ height: 100px; margin: 20px; background: red; } .a1{ background: green; } <!DOCTYPE html> <html> <head> </head> <body> ...

Updating the text box's font color to its original black shade

I have a form that includes dynamic text boxes fetching data from the backend. When a user clicks on a text box, the color of the text changes. Upon form submission, a confirmation message is displayed and I want the text box color to revert back to black. ...

A guide on changing a plus sign into a minus sign with CSS transition

Is there a way to create a toggle button that changes from a plus sign to a minus sign using only CSS, without the need for pseudo-elements? The desired effect is to have the vertical line in the "+" sign shrink into the horizontal line. While I know it& ...