在两个字符串之间使用php xml解析器

时间:2013-03-22 12:49:49

标签: php xml string

<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>

我想在 <![CDATA[ ]]> 之间复制文本,然后将其粘贴到 alt 属性中。< / p>

上面的例子应该是;

<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>

有可能吗? 如果可能的话,如何做到这一点是合理的?

1 个答案:

答案 0 :(得分:0)

您可以删除htmlspecialchars,因为它仅用于测试目的。 正如@michi所说,你需要有效的xml。每个组都应该在一个块容器中,例如<example>stuff </example>,如下所示

测试数据

<?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;

输出代码

$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>
');
 }
?>