-3

Hi guys its my 1st time here i have spent so many hours actually just to find out how i can do it.

Jquery clone can easily do it for me but the downside is that i can not use it for SEO purpose s.

So i want an alternative by using PHP to copy text inside a tag and echo it anywhere.

<div class="content-to-copy" id="content-to-copy">Copy this text</div>
<div class="content-new-location" class="content-new-location"></div>

I can easily acheive the above by using jquery clone by using the codes below

jquery clone code pen

How can I do it using PHP?

asprin
  • 9,579
  • 12
  • 66
  • 119

1 Answers1

0

Alternatively, (simple html dom parser is good actually), you could use DOMDocument in conjunction with DOMXpath on this one. Consider this example:

$original_html = '<div class="content-to-copy" id="content-to-copy">Copy this text</div><div id="content-new-location" class="content-new-location"></div>';
$dom = new DOMDocument;
@$dom->loadHTML($original_html);
$xpath = new DOMXpath($dom);

// clone
$clone = $xpath->query('//div[@id="content-to-copy"]//text()');
$clone_value = (string) $clone->item(0)->nodeValue;
$xpath->query('//div[@id="content-new-location"]')->item(0)->nodeValue = $clone_value;
// extra styling to see difference
$xpath->query('//div[@id="content-new-location"]')->item(0)->setAttribute('style', 'color: red; font-weight: bold;');

$final_html = $dom->saveHTML($dom);

echo $final_html;

Sample Output

user1978142
  • 7,946
  • 3
  • 17
  • 20