[ create a new paste ] login | about

Project: saji89
Link: http://saji89.codepad.org/2TyOAibZ    [ raw code | output | fork | 1 comment ]

saji89 - PHP, pasted on Aug 21:
<?php
$dom = new DomDocument();
$test='<p class="Heading1-P">
    <span class="Heading1-H">Chapter 1</span>
</p>
<p class="Normal-P">
    <span class="Normal-H">This is chapter 1</span>
</p>
<p class="Heading1-P">
    <span class="Heading1-H">Chapter 2</span>
</p>
<p class="Normal-P">
    <span class="Normal-H">This is chapter 2</span>
</p>
<p class="Heading1-P">
    <span class="Heading1-H">Chapter 3</span>
</p>
<p class="Normal-P">
    <span class="Normal-H">This is chapter 3</span>
</p>';

$dom->loadHTML($test);
$xpath = new DOMXpath($dom);
$heading=parseToArray($xpath,'Heading1-H');
$content=parseToArray($xpath,'Normal-H');

var_dump($heading);
echo "<br/>";
var_dump($content);
echo "<br/>";

function parseToArray($xpath,$class)
{
	$xpathquery="//span[@class='".$class."']";
	$elements = $xpath->query($xpathquery);

	if (!is_null($elements)) {	
		$resultarray=array();
		foreach ($elements as $element) {
		    $nodes = $element->childNodes;
		    foreach ($nodes as $node) {
		      $resultarray[] = $node->nodeValue;
		    }
		}
		return $resultarray;
	}
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
array(3) {
  [0]=>
  string(9) "Chapter 1"
  [1]=>
  string(9) "Chapter 2"
  [2]=>
  string(9) "Chapter 3"
}
<br/>array(3) {
  [0]=>
  string(17) "This is chapter 1"
  [1]=>
  string(17) "This is chapter 2"
  [2]=>
  string(17) "This is chapter 3"
}
<br/>


Create a new paste based on this one


Comments:
posted by alancito343 on Feb 18
I like this code. Congratulations.
reply