与类别匹配时,XML Feed中的输出项

时间:2017-09-07 18:09:29

标签: php xml wordpress categories

我已经从我的商店导出了所有产品作为XML文件,并在我的主题的single.php中使用PHP解析了这些项目。到目前为止,该解析工作正常。

现在我想只显示类别名称与WP文章编辑器中设置的产品相匹配的产品。这是我的代码:

<?php

    // Parse XML Feed
    $html = "";
    $url = "http://example.com/feed.xml";
    $xml = simplexml_load_file($url);
    $item = $xml->channel->item;
    $categories = get_the_category();

    for($i = 0; $i < count($item); $i++){
        $title = $item[$i]->title;
        $link = $item[$i]->link;
        $category = $item[$i]->category;
        $img = $item[$i]->description->a->img["src"];

        // This approach breaks my site. A loop in another loop seems not to be that good
        // foreach ($categories as $i => $cat) {
        //   $catName = $cat->name;

        //   if (preg_match("/\b$catName\b/", $category)) {
        //     $html .= "
        //       <a href='$link'><h3>$title</h3>
        //       <img src='$img'>
        //       <p>$category</p></a>
        //       <hr>";
        //     }
        //   }

        if (preg_match("/\bCATEGORY_NAME\b/", $category)) {
          $html .= "
        <a href='$link'><h3>$title</h3>
        <img src='$img'>
        <p>$category</p></a>
        <hr>";
        }
    }

    echo $html;
  ?>

如果我将CATEGORY_NAME更改为退出的类别名称,那么输出就像我想要的那样。使用该循环的另一种方法会破坏我的网站“致命错误:允许的内存大小为***字节耗尽......”。

很想听到一些提示

编辑:这是一些示例代码

<?xml version="1.0" encoding="UTF-8"?>
    <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <atom:link href="www.example.com/export.xml" rel="self" type="application/rss+xml" />
        <title>www.example.com</title>
        <description>desc</description>
        <link>www.example.com</link>
        <language>1-1</language>
        <image>
            <url>www.example.com/logo.gif</url>
            <title>test page</title>
            <link>http://example.com</link>
        </image>
        <item>
            <title>Example item</title>
            <guid>www.example.com/item</guid>
            <link>www.example.com/item</link>
            <description>
                <a href="www.example.com/item" style="border:0 none;">
                    <img src="www.example.com/image.png" align="right" style="padding: 0pt 0pt 12px 12px; float: right;" />
                </a>
            </description>
            <category>Categoryname</category>
            <pubDate>Thu, 24 Aug 2017 17:19:17 +0200</pubDate>rn</item>
    </channel>
</rss>

0 个答案:

没有答案
相关问题