为了账号安全,请及时绑定邮箱和手机立即绑定

PHP RSS XML 再次解析、过滤和展示

PHP RSS XML 再次解析、过滤和展示

PHP
元芳怎么了 2023-05-26 17:52:11

我正在使用DOMDocument. 那很好用。我需要解析我的 XML,找到特定的值,然后只再次显示某些节点。


XML 看起来像这样......


<rss version="2.0">

  <channel>

  <title>Title</title>

  <link></link>

  <item>

    <title>Title #1</title>

    <description>Here I want to filter</description>

  </item>

  <item>

    <title>Title #2</title>

    <description>Should not be displayed</description>

  </item>

</channel>

我想在描述标签内搜索,如果找到关键字我想显示item. 如果找不到,我想删除 parent item。


到目前为止,这就是我尝试过的...


<?php


header('Content-Type: text/xml');


// Load our XML document

$rss = new DOMDocument();

$rss->load('https://myurl');


$description = $rss->getElementsByTagName('description');


foreach ($description as $node) {

    $s = $node->nodeValue;


    if (strpos($s, 'filter') !== false)

    {

      //found the keyword, nothing to delete

    }

    else

    {

      //didnt find it, now delete item

      $node->parentNode->parentNode->removeChild($node->parentNode);

    }

}


echo $description->saveXml();

我正在尝试获取所有描述节点,检查它们是否包含字符串,如果不包含,则删除父节点。搜索字符串有效,但删除节点无效。如果我回显我的 XML,则没有任何改变。


查看完整描述

1 回答

?
慕桂英3389331

TA贡献1871条经验 获得超8个赞

getElementsByTagName()将返回“实时”结果。如果您修改文档,它将发生变化。您可以用来iterator_to_array()制作稳定的副本。


另一种选择是使用 Xpath 表达式来获取特定节点。


$document = new DOMDocument();

$document->loadXML($xmlString);

$xpath = new DOMXpath($document);


// fetch items that contain "filter" in their description

$items = $xpath->evaluate('/rss/channel/item[contains(description, "filter")]');

foreach ($items as $item) {

    // dump the title child element text content

    var_dump($xpath->evaluate('string(title)', $item));


// fetch items that do not contain "filter" in their description

$items = $xpath->evaluate('/rss/channel/item[not(contains(description, "filter"))]');

foreach ($items as $item) {

    // remove item element

    $item->parentNode->removeChild($item);

echo $document->saveXML();

输出:


string(8) "Title #1"

<?xml version="1.0"?>

<rss version="2.0">

  <channel>

  <title>Title</title>

  <link/>

  <item>

    <title>Title #1</title>

    <description>Here I want to filter</description>

  </item>


</channel>

</rss>


查看完整回答
反对 回复 2023-05-26
  • 1 回答
  • 0 关注
  • 17 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信