如何从复杂的XML中解析文本和图像 [英] How to parse text and image from complex xml

查看:38
本文介绍了如何从复杂的XML中解析文本和图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望你能帮我这个忙。该XML文件如下所示:

<channel><item>
<description>
<div>  <a href="http://image.com">
<span>   
<img src="http://image.com" /> 
</span>
</a>
Lorem Ipsum is simply dummy text of the printing etc... 
</div>
</description>
</item></channel>

我可以获得Description标记的内容,但当我这样做时,我会得到整个结构,其中包含许多CSS,我不想要这样的内容。 我真正需要的是只解析href链接和Lorem Ipsum文本。我正在尝试使用简单的XML,但找不到,看起来太复杂了。有什么想法吗?

编辑: 我用来解析XML的代码

$file = new SimpleXMLElement($mydata);
{

    foreach($file->channel->item as $post)
{

    echo $post->description; } }

推荐答案

这是回答问题的最终代码。

$xml = simplexml_load_file('myfile.xml');

$descriptions = $xml->xpath('//item/description');

foreach ( $descriptions as $description_node ) {

    $description_dom = new DOMDocument();
    $description_dom->loadHTML( (string)$description_node );

    $description_sxml = simplexml_import_dom( $description_dom );

    $imgs = $description_sxml->xpath('//img');
    $text = $description_sxml->xpath('//div');

    foreach($imgs as $image){

    echo (string)$image['src'];     
       }
    foreach($text as $t){

        echo (string)$t;
       }
    }

这是IMSoP的代码,我添加了$text = $description_sxml->xpath('//div');来读取<div>中的文本。

在我的例子中,XML中的一些帖子有多个<div><span>标记,因此要解析所有它们,我可能必须为<span>添加另一个->xpathif... else语句,以便如果<div>中没有任何内容,则回显<span>内容。 感谢您的回复。

这篇关于如何从复杂的XML中解析文本和图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆