How to do a search in an xml file with php?

0
<ISBN id = "1">
        <genero>
            <descricao>
                Suspense
            </descricao>
            <descricao>
                Ficcao Policial
            </descricao>
        </genero>
        <titulo>
            Assassinato no expresso do oriente
        </titulo>
        <autor>
            Agatha Christie
        </autor>
        <publicacao>
            1934
        </publicacao>
    </ISBN>

Personal, I want to create a system in PHP so that based on the xml file above, the user can type, for example, suspense and search for all books with that genre. Does anyone know how I can do this? (The original xml is composed of 8 books structured this way)

    
asked by anonymous 02.03.2018 / 22:09

1 answer

0

You can use SimpleXMLElement to work with XML on PHP .

When you use it, you will receive an element with the xpath method. With this method you can use expressions to filter out some values, for example:

$livros = $simpleXML->xpath("//genero//*[contains(text(), 'genero')]/../..");

In this way we access all elements genero and check with contains , if the text has the desired genre. Then we return the node ISBN with the ../../

Full Code:

<?php

$pesquisa = "Assassinato";

$xml = <<<XML
<Livros>
    <ISBN id="978-8547216696">
        <genero>
            <descricao>Direito</descricao>
            <descricao>Psicologia</descricao>
        </genero>

        <titulo>
            Insania Furens. Casos Verídicos de Loucura e Crime
        </titulo>

        <autor>
            Guido Arturo Palomba
        </autor>

        <publicacao>
            2017
        </publicacao>
    </ISBN>

    <ISBN id="978-8594540386">
        <genero>
            <descricao>Psicologia</descricao>
        </genero>

        <titulo>
            Arquivos Serial Killers. Made in Brazil e Louco ou Cruel
        </titulo>

        <autor>
            Ilana Casoy
        </autor>

        <publicacao>
            2017
        </publicacao>
    </ISBN>

    <ISBN id="978-8594540133">
        <genero>
            <descricao>Histórias Reais</descricao>
            <descricao>Assassinato e Mutilação</descricao>
        </genero>

        <titulo>
            Casos de Família: Arquivos Richthofen e Arquivos Nardoni
        </titulo>

        <autor>
            Ilana Casoy
        </autor>

        <publicacao>
            2016
        </publicacao>
    </ISBN>
</Livros>
XML;

$simpleXML = new SimpleXMLElement($xml);

$livros = $simpleXML->xpath("//genero//*[contains(text(), '{$pesquisa}')]/../..");

foreach($livros as $livro) {
    $titulo = trim(reset($livro->xpath("./titulo")[0]));

    echo "Título: {$titulo}\n";
}
    
03.03.2018 / 03:11