views:

88

answers:

2

I have a string (not xml )

<headername>X-Mailer-Recptid</headername>
<headervalue>15772348</headervalue>
</header>

from this, i need to get the value 15772348, that is the value of headervalue. How is possible?

+10  A: 

Use PHP DOM and traverse the headervalue tag using getElementsByTagName():

<?php
$doc = new DOMDocument;
@$doc->loadHTML('<headername>X-Mailer-Recptid</headername><headervalue>15772348</headervalue></header>');

$items = $doc->getElementsByTagName('headervalue');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}
?>

This gives the following output:

15772348

[EDIT]: Code updated to suppress non-HTML warning about invalid headername and headervalue tags as they are not really HTML tags. Also, if you try to load it as XML, it totally fails to load.

shamittomar
+1 Parse it the way it's meant to be parsed.
BoltClock
it output the answer, but also getting some warningWarning: DOMDocument::loadHTML() [function.DOMDocument-loadHTML]: Tag headername invalid in Entity, line: 1 in C:\wamp\www\test.php on line 496Warning: DOMDocument::loadHTML() [function.DOMDocument-loadHTML]: Tag headervalue invalid in Entity, line: 1 in C:\wamp\www\test.php on line 496Warning: DOMDocument::loadHTML() [function.DOMDocument-loadHTML]: Unexpected end tag : header in Entity, line: 1 in C:\wamp\www\test.php on line 496
Linto P D
@Linto, I have updated the code to suppress the warning. Try new code now.
shamittomar
ok thanks BoltClock
Linto P D
@Linto: you're... welcome? :O
BoltClock
It will fail to load as XML because there is no root element.
BoltClock
@Boltclock: yes, that's why I made it clear by editing the edit :)
shamittomar
+1  A: 

This looks XML-like to me. Anyway, if you don't want to parse the string as XML (which might be a good idea), you could try something like this:

<?
$str = "<headervalue>15772348</headervalue>";
preg_match("/<headervalue\>([0-9]+)<\/headervalue>/", $str, $matches);
print_r($matches);
?>
Michael Mior
It's ok for simple things like this, but obligatory warning about using regular expressions to parse non-regular languages. [That way lies madness](http://stackoverflow.com/questions/1732348/1732454#1732454).
James
@James I agree.
Michael Mior