DOM manipulation with PHP

I would like to do a simple yet non-trivial manipulation of DOM elements with PHP, but I am lost.

Suppose a page like Wikipedia contains paragraphs and titles ( <p>

, <h2>

). They are brothers and sisters. I would like to take both items in sequential order.

I tried GetElementbyName

, but then you have no way to organize the information. I tried it DOMXPath->query()

, but I found it really confusing.

Just parse something like:

<html>
  <head></head>
  <body>
    <h2>Title1</h2>
    <p>Paragraph1</p>
    <p>Paragraph2</p>
    <h2>Title2</h2>
    <p>Paragraph3</p>
  </body>
</html>

      

at

Title1
Paragraph1
Paragraph2
Title2
Paragraph3

With a few bits of HTML, I don't need it in between.

Thanks. Hope the question doesn't sound like homework.

+1


a source to share


3 answers


I think that DOMXPath->query()

is the right approach. This XPath expression will return all nodes that are either <h2>

at or <p>

at the same level (since you said they were siblings).

/ html / body / * [name () = 'p' or name () = 'h2']


The nodes will be returned as a node list in the correct order (document order). Then you can build a foreach loop over the result.

+1


a source


I have a simple html dom by SCChen several times.

Ideal class for accessing dom elements.

Example:



// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 

      

Check it out here. simplehtmldom

May help with future projects

+1


a source


Try to take a look at this library and related project:

Simple HTML DOM

This allows you to open an online page or html page from the file system and access its elements via class names, tag names, and IDs. If you are familiar with jQuery and its syntax, you do not need to get used to this library.

+1


a source







All Articles