0

I would like to extract both attributes BODY and TYPE from the following xml and output the TYPE as div class and body as text.

For example:

foreach (...) {
echo "<div class='$type_value'>$body_value</div>"
}

My XML:

<smses>
<sms body='something' type='1' address='1234'>
<sms body='something' type='2' address='12345'>
<sms body='something' type='2' address='1234'>
</smses>

My code (so far extracting only one attribute - body):

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

$path = new Domxpath($doc);

$num = $_POST["sel"];

$result = $path->query("//smses/sms[@address='$num']/@body");

foreach($result as $res)
{
echo "<div id='sms'>".$res->textContent.'</div><br/><br/>';
}
1
  • 1
    Get the matching sms elements (rather than their body attribute), and use getAttribute() within the loop. Commented Feb 12, 2013 at 11:31

1 Answer 1

2

Remove /@body from the XPath so that you select the actual <sms> element, using that you can get the type attribute and its body text into the <div>:

$result = $path->query("//smses/sms[@address='$num']");

foreach($result as $res)
{
    echo "<div id='sms' class='" . $res->getAttribute("type") . "'>". $res->getAttribute("body").'</div><br/><br/>';
}

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Do i also have to change textContent to getAttribute("body")?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.