使用 PHP (simplexml) 根据 XML 中的内容排除子项
关于 PHP 和 XML 的另一个问题...
是否可以根据儿童内容排除儿童。
请参阅下面的示例: 如果“标题”包含“XTRA:”一词,我不希望列出此“电影”。
这是我的 PHP 代码:
<? $xml = simplexml_load_file("movies.xml");
foreach ($xml->movie as $movie){ ?>
<h2><? echo $movie->title ?></h2>
<p>Year: <? echo $movie->year ?></p>
<? } ?>
这是我的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<movies>
<movie>
<title>Little Fockers</title>
<year>2010</year>
</movie>
<movie>
<title>Little Fockers XTRA: teaser 3</title>
<year>2010</year>
</movie>
</movies>
上面代码的结果是:
<h2>Little Fockers</h2>
<p>Year: 2010</p>
<h2>Little Fockers XTRA: teaser 3</h2>
<p>Year: 2010</p>
我希望它只是:
<h2>Little Fockers</h2>
<p>Year: 2010</p>
Another question about PHP and XML...
Is it posible to exclude children based on there childrens content.
See the example below:
If "title" contains the word "XTRA:" I don't want this "movie" to be listed.
This is my PHP code:
<? $xml = simplexml_load_file("movies.xml");
foreach ($xml->movie as $movie){ ?>
<h2><? echo $movie->title ?></h2>
<p>Year: <? echo $movie->year ?></p>
<? } ?>
This is mys XML file:
<?xml version="1.0" encoding="UTF-8"?>
<movies>
<movie>
<title>Little Fockers</title>
<year>2010</year>
</movie>
<movie>
<title>Little Fockers XTRA: teaser 3</title>
<year>2010</year>
</movie>
</movies>
The outcome of the code above is:
<h2>Little Fockers</h2>
<p>Year: 2010</p>
<h2>Little Fockers XTRA: teaser 3</h2>
<p>Year: 2010</p>
I want it to be only:
<h2>Little Fockers</h2>
<p>Year: 2010</p>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两种方法可以过滤节点。第一个是 XPath 1.0(libxml/SimpleXML 支持的版本)
,这里我们使用包含函数,这相当于 XPath 的 PHP 的 strpos()。不幸的是,XPath 1.0 只有几个字符串函数,并且所有函数都区分大小写。因此,虽然 XPath 非常适合处理复杂的层次结构,但它不太擅长处理字符串。在这种情况下,您可以回退到 PHP 解决方案,例如:
There are two ways to filter nodes. The first is with XPath 1.0 (the version supported by libxml/SimpleXML)
Here, we use the contains function, which is XPath's equivalent to PHP's strpos(). Unfortunately, XPath 1.0 only has a few string functions and all of them are case sensitive. So while XPath is very adapted to handle complex hierarchy, it's not so good at dealing with string. In that case, you can fallback to a PHP solution such as: