Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [HTML][PHP]Wyciągnięcie atrybutu z taga i wstawienie go do innego
Forum PHP.pl > Forum > Przedszkole
Laran
Witam.

Chciałbym zamienić wartość atrybutu "href" tagu "a" na wartość atrybutu "src" tagu "img". Przykład obecnego kodu:
  1. <a class="image" href="http://example.com/index.php?title=File:example.jpg">
  2.  
  3. <img width="48" height="48" src="http://example.com/images/9/90/example.jpg" alt="Bombing.jpg"></img>
  4.  
  5. </a>

Rezultat jaki chce osiągnąć to:
  1. <a class="image" href="http://example.com/images/9/90/example.jpg">
  2.  
  3. <img width="48" height="48" src="http://example.com/images/9/90/example.jpg" alt="Bombing.jpg"></img>
  4.  
  5. </a>

Proszę o pomoc, bo nie mam pojęcia jak to ugryźć.

Pozdrawiam.
rocktech.pl
Witam.


Zacznij od tego ...

  1. $HTMLs = '<a class="image" href="http://example.com/index.php?title=File:example.jpg">
  2. <img width="48" height="48" src="http://example.com/images/9/90/example.jpg" alt="Bombing.jpg"></img>
  3. </a>';
  4.  
  5. libxml_use_internal_errors(true);
  6. $html = new DOMDocument();
  7. $html->validateOnParse = false;
  8. $html->loadHTML($HTMLs);
  9.  
  10. foreach ( $html->getElementsByTagName('a') as $a) {
  11. echo $a->getAttribute('href');
  12. }
Laran
Wielkie dzięki za pomoc. Rezultat końcowy:

  1. function imageHref($content, $class)
  2. {
  3. libxml_use_internal_errors(true);
  4. $html = new DOMDocument();
  5. $html->validateOnParse = false;
  6. $html->loadHTML($content);
  7. $finder = new DomXPath($html);
  8. $nodes = $finder->query('//a[@class="'.$class.'"]');
  9.  
  10. foreach ($nodes as $a)
  11. {
  12. foreach ($a->getElementsByTagName('img') as $a2)
  13. {
  14. $new = $a2->getAttribute('src');
  15.  
  16. $a->removeAttribute('href');
  17. $a->setAttribute('href', $new);
  18. }
  19. }
  20.  
  21. $content = $html->saveHTML();
  22. return $content;
  23. }


Temat do zamknięcia.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.