user3619039
user3619039

Reputation: 47

Read XML commented value

Helo,
I have an XML file. I want to do read commented value(100001) and line number. PHP/Ajax auto complete need, when I put serial number in textbox, it should show XML line number and commented value inside another 2 textboxes. I have no idea how to do this, if any one can help, I will really respect about it.

<serial>KLH4587KIJ</serial> <!--    100001  -->
<serial>MHF4557PDS</serial> <!--    100002  -->

Upvotes: 0

Views: 117

Answers (1)

tomloprod
tomloprod

Reputation: 7890

Use the next code:

$doc = new DOMDocument;
$doc->loadXML('<serials><serial>KLH4587KIJ</serial><!-- 100001 --><serial>MHF4557PDS</serial><!-- 100002 --></serials>');

$xpath = new DOMXPath($doc);

foreach ($xpath->query('//comment()') as $comment){
    var_dump($comment->textContent);
}

As you can see, you have to encapsulate the serial tag in a parent serials

You can see it works here: http://codepad.org/UoZvPxjl


Edit. Added line number:

$doc = new DOMDocument;
$doc->loadXML('<serials><serial>KLH4587KIJ</serial><!-- 100001 --><serial>MHF4557PDS</serial><!-- 100002 --></serials>');

$xpath = new DOMXPath($doc);
$lineNo = 0;
foreach ($xpath->query('//serial/following::comment()') as $comment){
    $serial= $xpath->query('//serial', $comment)->item($lineNo)->textContent;
    var_dump ("Line number: ".$lineNo ." Serial number: ".$serial." Comented number: ".$comment->textContent);
    $lineNo++;
}

You can see this in action here: http://codepad.org/4igoDzWN

Upvotes: 4

Related Questions