简体   繁体   中英

Exclude children based on content in XML with PHP (simplexml)

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>

There are two ways to filter nodes. The first is with XPath 1.0 (the version supported by libxml/SimpleXML)

$movies = simplexml_load_file("movies.xml");

foreach ($movies->xpath('movie[not(contains(title, "XTRA:"))]') as $movie)
{
    echo '<h2>', $movie->title, '</h2>';
}

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:

$movies = simplexml_load_file("movies.xml");

foreach ($movies->movie as $movie)
{
    if (stripos($movie->title, 'XTRA:') !== false)
    {
        // skip to next iteration
        continue;
    }

    echo '<h2>', $movie->title, '</h2>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM