<title><![CDATA[ hello
]]></title>
<link>http://www.google.com</link>
<description><img class="img" src="http://google.com/a.jpg" alt="" /></a>]]></description>
<title><![CDATA[ good
]]></title>
<link>http://www.google.com</link>
<description><img class="img" src="http://google.com/b.jpg" /></a>]]></description>
<title><![CDATA[ world
]]></title>
<link>http://www.google.com</link>
<description><img class="img" src="http://google.com/c.jpg" alt="" /></a>]]></description>
I want to copy the text between <![CDATA[
and ]]>
then paste them into alt attribute.
The example above should be;
<title><![CDATA[ hello
]]></title>
<link>http://www.google.com</link>
<description><img class="img" src="http://google.com/a.jpg" alt="hello" /></a>]]></description>
<title><![CDATA[ good
]]></title>
<link>http://www.google.com</link>
<description><img class="img" src="http://google.com/b.jpg" /></a>]]></description>
<title><![CDATA[ world
]]></title>
<link>http://www.google.com</link>
<description><img class="img" src="http://google.com/c.jpg" alt="world" /></a>]]></description>
Is it possible? How to do it would be reasonable, if possible?
You can remove htmlspecialchars
as it was just for test purposes. As @michi says you need valid xml. Each group should be in a block container For Example <example>stuff </example>
as below
test data
<?php
$testdata = <<<XML
<?xml version='1.0'?>
<test>
<example>
<title><![CDATA[ example 1]]></title>
<link>http://www.example1.com</link>
<description><![CDATA[ <img class="img" src="http://google.com/a.jpg" alt="" /></a>]]></description>
</example>
<example>
<title><![CDATA[ example 2]]></title>
<link>http://www.example2.com</link>
<description><![CDATA[ <img class="img" src="http://google.com/b.jpg" /></a>]]></description>
</example>
<example>
<title><![CDATA[ example 3 ]]></title>
<link>http://www.example3.com</link>
<description><![CDATA[ <img class="img" src="http://google.com/c.jpg" alt="" /></a>]]></description>
</example>
</test>
XML;
output code
$xml = simplexml_load_string($testdata, 'SimpleXMLElement', LIBXML_NOCDATA);
foreach ($xml->example as $v){
// find and replace alt
$img = str_replace( 'alt=""','', $v->description);
$img = str_replace( '<img','<img alt="'.$v->title.'"', $img);
echo htmlspecialchars(
'
<example>
<title><![CDATA[ '.$v->title.']]></title>
<link>'.$v->link.'</link>
<description><![CDATA[ '.$img.'</a>]]></description>
</example>
');
}
?>