PHP Xpath多个节点

时间:2013-02-12 11:28:51

标签: php xpath domxpath

我想从以下xml中提取属性BODY和TYPE,并将TYPE输出为div类,将body输出为文本。

例如:

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

我的XML:

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

我的代码(到目前为止只提取一个属性 - 正文):

$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 个答案:

答案 0 :(得分:1)

从XPath中删除/@body,以便您选择实际的<sms>元素,使用该元素可以将type属性及其正文添加到<div>:< / p>

$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