Atributos para un array de elementos con DiDom
al hacer parsing en PHP
Ahora, al iterar sobre el array de elementos, obtengamos sus atributos. Supongamos que tenemos el siguiente texto con enlaces:
<a href="1.html">1</a>
<a href="2.html">2</a>
<a href="3.html">3</a>
Obtengamos un array de estos enlaces:
<?php
$elems = $document->find('a');
?>
Iteremos sobre ellos con un bucle y mostremos el contenido
de sus atributos href
:
<?php
foreach ($elems as $elem) {
echo $elem->href . '<br>';
}
?>
Y ahora recolectemos sus atributos en un array:
<?php
$res = [];
foreach ($elems as $elem) {
$res[] = $elem->href;
}
var_dump($res);
?>
Obtenga un array de las rutas a las imágenes:
<img src="img1.png">
<img src="img2.png">
<img src="img3.png">
Se dan los siguientes enlaces:
<a href="1.html">1</a>
<a href="2.html">2</a>
<a href="3.html">3</a>
Obtenga las URLs y los textos de los enlaces en forma del siguiente array bidimensional:
<?php
[
[
'href' => '1.html',
'text' => '1',
],
[
'href' => '2.html',
'text' => '2',
],
[
'href' => '3.html',
'text' => '3',
],
]
?>