1

This is my PHP/XML code. I just want to search the particular $searchterm from this:

$doc = new DOMDocument;
$doc->load('authentication.xml');

$xpath = new DOMXPath($doc);

$searchTerm = "N0A097016646";

$lineNo = 0;
foreach ($xpath->query('//device/following::comment()') as $comment){
    $serial= $xpath->query('//device', $comment)->item($lineNo)->textContent;

    echo "Line number: ".$comment->getLineNo()." Device number: ".$serial." Comented number: ".$comment->textContent."<br>";

    $lineNo++;
}

Where should I put the $searchTerm variable to search that particular node?

Chuck
  • 998
  • 8
  • 17
  • 30
user3619039
  • 47
  • 1
  • 8
  • use your `$searchTerm` inside your xpath query, its not used. research about `contains()` – Kevin Dec 29 '14 at 06:47
  • I tried it, but doesn't work : $serial= $xpath->query('//device[contains("'.$searchTerm.'")]', $comment)->item($lineNo)->textContent; – user3619039 Dec 29 '14 at 06:49
  • do you have a sample xml to work with? hard to guess on this end – Kevin Dec 29 '14 at 06:52
  • Hi, Yes, and also I no need to use that $lineNo variable. but when I remove, it will show some error. I can get line number using getLineNo() function, this is my sample xml file J0A0AM049303 H0A0AG014628 N0A097016646 – user3619039 Dec 29 '14 at 06:55

1 Answers1

1

As your question stands you haven't use the $searchTerm.

Use it with = (equal)

text() = '$searchTerm'

Code:

$searchTerm = "N0A097016646";

foreach ($xpath->query("//device[text() = '$searchTerm']/following::comment()") as $comment){
    echo "Line number: ".$comment->getLineNo(). '<br/>'.
    " Device number: ".$searchTerm.'<br/>'.
    " Comented number: ". $comment->textContent."<hr>";
}

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
  • Hi, but I only want 1 result according to that $searchTerm; but this shows everything again. please help to resolve it this is my xml: ; J0A0AM049303 H0A0AG014628 N0A097016646 – user3619039 Dec 29 '14 at 07:12
  • @user3619039 and also be wary of xpath injection also if this a user input http://dl.packetstormsecurity.net/papers/attack/xpath-injection.pdf http://stackoverflow.com/questions/188834/cleaning-sanitizing-xpath-attributes – Kevin Dec 29 '14 at 07:25