【发布时间】:2015-05-20 05:40:54
【问题描述】:
我有一个项目列表,我需要在其中获取列表标题属性、链接 URL 和显示的链接文本,以及每个列表标记的跨度值。
<ul>
<li class="testclass" title="Title 1 goes here">
<a href="http://examplelink1.com">List Text 1</a>
<span>Second List Text 1</span>
</li>
<li class="testclass" title="Title 2 goes here">
<a href="http://examplelink2.com">List Text 2</a>
<span>Second List Text 2</span>
</li>
</ul>
如何使用 foreach 提取每个单独的列表标签及其值(因为之后我需要将值插入 MySQL 数据库(每个值在不同的数据库字段中)。
到目前为止,我只能分别获得它们:
<?php
$doc = new DOMDocument();
@$doc->loadHTML($list);
$imageTags = $doc->getElementsByTagName('a');
foreach($imageTags as $tag) {
$link = $tag->getAttribute('href');
echo $link.'<br/>';
}
?>
和
<?php
$doc = new DOMDocument();
@$doc->loadHTML($list);
$imageTags = $doc->getElementsByTagName('li');
foreach($imageTags as $tag) {
$link = $tag->getAttribute('title');
echo $link.'<br/>';
}
?>
我找到了一个带有 xpath 的脚本,但我不知道如何正确应用它来获取我需要的特定值并在 MySQL 语句中使用它们:
<?php
$dom = new DOMdocument();
@$dom->loadHTML($list);
$xpath = new DOMXPath($dom);
$elements = $xpath->query("//*");
foreach ($elements as $element) {
echo "<p>". $element->nodeName. "</p>";
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "<br/>";
}
}
?>
【问题讨论】:
标签: php dom xpath foreach nodes