Search code examples
zend-framework2

load xml file instead of xml string by using Zend\Dom\Query?


In a nutshell

 public function testAction() {
    $html = '<div>
                <table>
                    <tr>
                        <td class="foo">
                            <div>
                                Lorem ipsum <span class="bar">
                                    <a href="/foo/bar" id="one">One</a>
                                    <a href="/foo/baz" id="two">Two</a>
                                    <a href="/foo/bat" id="three">Three</a>
                                    <a href="/foo/bla" id="four">Four</a>
                                </span>
                            </div>
                        </td>
                    </tr>
                </table>
                </div>';
    $dom = new Query($html);
    $results = $dom->execute('.foo .bar a');

    return new ViewModel(array(
        'results' => $results,
            )
    );
}

For now I put string of xml directly in code. How could I pass it from file.

Something like:

$dom = new Query($sourceXMLFile);
    $results = $dom->execute('.foo .bar a');

    return new ViewModel(array(
        'results' => $results,
            )
    );

How can I do this with zend2? Because I can not find any document references.


Solution

  • You can use the file_get_contents() PHP function for reading the content of the XML file and put it in a variable:

    $var = file_get_contents('your.xml');
    

    Here is the documentation for this function: http://www.php.net/manual/ru/function.file-get-contents.php

    Once you have your XML in a variable, you can pass it to the Query class' constructor.