Не был протестирован или скомпилирован, но одним из способов является создание функции, которая использует PHP: DOMDocument и его метод getElementsByTagName
, который возвращает
PHP: DOMNodeList , что вы можете получить доступ к узлу по определенному индексу.
function grabAttributes($file, $tag, $index) {
$dom = new DOMDocument();
if (!@$dom->load($file)) {
echo $file . " doesn't exist!\n";
return;
}
$list = $dom->getElementsByTagName($tag); // returns DOMNodeList of given tag
$newElement = $list->item($index)->nodeValue; // initialize variable
return $newElement;
}
Если вы позвоните grabAttributes("myfile.html", "li", 2)
, переменная будет установлена на "Third List"
Или вы можете создать функцию для помещения всех атрибутов данного тега в массив.
function putAttributes($file, $tag) {
$dom = new DOMDocument();
if (!@$dom->load($file)) {
echo $file . " doesn't exist!\n";
return;
}
$list = $dom->getElementsByTagName($tag); // returns DOMNodeList of given tag
$myArray = array(); // array to contain values.
foreach ($list as $tag) { // loop through node list and add to an array.
$myArray[] = $tag->nodeValue;
}
return $myArray;
}
Если вы позвоните putAttributes("myfile.html", "li")
, он вернет array("First List", "Second List", "Third List")