0

first I need to find all img in the sites, and then check if the img have the "alt" attribute, if image have the attribute it'll be escaped and if it not have one or the alt is empty,a string will be randomly added to img from a list or array.

here is how you do it with javascript: find if a img have alt in jquery if not then add from array

but it did not help me because according to this: How do search engines crawl Javascript?

search bots can't read it , if you use JavaScript you need to use server-side language to add keyword to img alt.

what next? php? can i do it with a simple code?

Community
  • 1
  • 1
E P
  • 389
  • 4
  • 16
  • 2
    *Randomly*? What sort of images do you have that you are able to select random but appropriate alt text? Don't try gaming search engines with fake alt text, it does more harm then good. – Quentin Jun 09 '12 at 21:38

1 Answers1

3

Well, import it into an DOMDocument object and find all images inside.

Seems rather trivial. See the DOMDocument class


Here's my code for the problem:

<?php

$html = <<<HTML
<html lang="en-US">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

  <p>
  <img src="test.png">
  <img src="test.jpg" alt="Testing">
  <img src="test.gif">
  </p>

</body>
</html>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$images = $dom->getElementsByTagName("img");
foreach ($images as $image) {
    if (!$image->hasAttribute("alt")) {
        $altAttribute = $dom->createAttribute("alt");
        $altAttribute->value = "Ready Value!";
        $image->appendChild($altAttribute);
    }
}
echo $dom->saveHTML();
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308