Friday, 15 May 2015

php - DOM loadhtml extract nodes and child nodes -


I have a list of items where I need to display the list title attribute, link url and link text, as well as Period value of each list tag.

  & lt; Ul & gt; & Lt; Li class = "testclass" title = "heading 1 goes here" & gt; & Lt; A href = "http://examplelink1.com" & gt; List Lesson 1 & lt; / A & gt; & Lt; Span & gt; Second list lesson 1 & lt; / Span & gt; & Lt; / Li & gt; & Lt; Li class = "test class" title = "heading 2 goes here" & gt; & Lt; A href = "http://examplelink2.com" & gt; List Lesson 2 & lt; / A & gt; & Lt; Span & gt; Second list lesson 2 & lt; / Span & gt; & Lt; / Li & gt; & Lt; / Ul & gt;  

How can I remove each person's list tag and its values ​​with a foreigner (since I need to include values ​​in mysql db later (each value in each db area ).

So far, I can only get them separately:

  & lt; php $ doc = new DOMDocument (); @ $ doc- & Load HTML ($ list); $ ImageTags = $ doc- & gt; getElementsByTagName ('a'); foreach ($ $ image tag as tag) {$ link = $ tag-> getAttribute (' Href '); copy $ l  

and

  & lt; php $ doc = new DOMDocument (); & lt; br / & gt;;}? & Gt; $ $ Doc-> Load HTML ($ list); $ ImageTags = $ doc- & gt; getElementsByTagName; foreach ($ $ image tag as $ tag) {$ link = $ tag- & GetAttribute ('title'); $ link echo '& lt; br / & gt;';}? & Gt;  

I found a script with Except, but I I do not know how to implement specific values ​​and to use them in a MySQL statement:

   Node vela "
"; }}? & Gt;

Use DOMXPath :: Evaluation () . This is part of ext / dom> and allows you to use XPath Expressions to fetch nodes and values ​​from the DOM. $ dom = new DOMDocument (); $ Dom- & gt; LoadHtml ($ HTML); $ Xpath = new DOMXPath ($ dom); Use xpath expression to get li nodes foreach ($ xpath- & gt; evaluate ('// ul / li [@ class = "testclass"]' as $ li- $ li {var_dump ([// This is a direct li attribute of li node; use the DOM method 'title' = & gt; $ li- & gt; getAttribute ('title'), // more complex, an xpath expression 'href' = & Gt; $ xpath- & gt; Assess ('string (a / @ href)', $ li), // text content 'link-text' => gt; $ xpath- & gt; string to evaluate Cast node in ('string (A) ', $ li), // works for a period, many' description '=> gt; $ xpath- & gt; evaluate (' string (period) ', $ li)]} < ("Title"] = & gt; string (17) "Heading 1 goes here" ["href" />>

output:

  array (4) "] => String (23)" http://examplelink1.com "[" link-text "] => string (11)" list text 1 "[" description "] = & gt; string ( 18) "second list lesson 1"} array (4) {["title"] => string (17) "title 2 goes here" ["href"] = & gt; String (23) "http://examplelink2.com" ["link-text"] = & gt; String (11) "List Lesson 2" ["Details"] = & gt; String (18) "Second List Text 2"}  

No comments:

Post a Comment