www.webdeveloper.com
Results 1 to 7 of 7

Thread: selecting xml in php

Hybrid View

  1. #1
    Join Date
    Jun 2008
    Posts
    18

    selecting xml in php

    folks i have this xml file
    Code:
    <greatpeople>
      <person>
        <firstname> Edward   </firstname>
        <name>      Jenner   </name>
      </person>
      <person>
        <firstname> Alan </firstname>
        <name>      Elion    </name>
      </person>
      <person>
        <firstname> Charles  </firstname>
        <name>      Babbage  </name>
      </person>
      <person>
        <firstname> Alan     </firstname>
        <name>      Touring  </name>
      </person>
      <person>
        <firstname> Ada      </firstname>
        <name>      Byron    </name>
      </person>
    
    </greatpeople>
    What i want is how can i apply PHP so that i can get all the information
    where person firstname== Alan so that i get following xml as result
    Code:
    <person>
        <firstname> Alan </firstname>
        <name>      Elion    </name>
      </person>
      <person>
        <firstname> Alan     </firstname>
        <name>      Touring  </name>
      </person>
    i have seen simple xml but that is only used for traversing... can any one tell how to do this in php??

  2. #2
    Join Date
    Mar 2007
    Location
    Athens, Greece
    Posts
    177
    Hi,

    Assume this is your XML file named "Names.xml" (in green color the nodes you want to collect)
    (I removed the leading and trailing spaces from text nodes -to avoid incorrect referenses of node values- ):

    "Names.xml":
    Code:
    <?xml version="1.0" encoding="iso-8859-1"?>
    <greatpeople>
      <person>
        <firstname>Edward</firstname>
        <name>Jenne</name>
      </person>
      <person>
        <firstname>Alan</firstname>
        <name>Elion</name>
      </person>
      <person>
        <firstname>Charles</firstname>
        <name>Babbage</name>
      </person>
      <person>
        <firstname>Alan</firstname>
        <name>Touring</name>
      </person>
      <person>
        <firstname>Ada</firstname>
        <name>Byron</name>
      </person>
    </greatpeople>
    May try this (uses DOM Functions of php 5):

    PHP Code:
    <?php

    // ----------------  The example uses the php 5 "DOM Functions"  to select specific node uding Xpath query ------------------ 

    $doc = new DOMDocument;                                        // Create a new dom document
    $doc->preserveWhiteSpace false;                              // Set features
    $doc->formatOutput true;                                     // Create indents on xml

    $doc->Load('Names.xml');                                        // Load the file

    $xpath = new DOMXPath($doc);
    $query '//greatpeople/person/firstname[. = "Alan"]';         // The xpath (starts from root node)
    $names $xpath->query($query);                                 // A list of matched elements


    $Output="";
    foreach (
    $names as  $node) {
       
    $Output.=$doc->saveXML($node->parentNode)."\n";             // We get the parent of  "<firstname>" element  (the entire "<person>" node and its children) (maybe get the parent node directly using xpath)
                                                                    // and use the saveXML() to convert it to string  
    }

    echo 
    $Output."<br>\n\n";                                      // The result 

    echo "<hr><br><b>Below view the results  as HTML content. &nbsp; (See also the page's HTML code):</b>\n<pre>".htmlspecialchars($Output)."</pre>";

    ?>
    You need php 5 for the above example.

    Cheers!

    Kostas
    Last edited by Kostas Zotos; 07-25-2008 at 09:17 AM.

  3. #3
    Join Date
    Jun 2008
    Posts
    18
    Hey dude

    firstly thanks alot.. I viewed the page source and it first gives xml and then html.

    i have a little confusion.. can i do xsl tranformation on above output e-g

    Code:
    <person>
      <firstname>Alan</firstname>
      <name>Elion</name>
    </person>
    <person>
      <firstname>Alan</firstname>
      <name>Touring</name>
    </person>
    Above is the output i got in the variable $output. Now i have a .xsl file that applies xsl transformations given an xml file as
    Code:
    $xp = new XsltProcessor();
        $xsl = new DomDocument('1.0','utf-8');
          $xsl->load('book.xsl');
    
      // import the XSL styelsheet into the XSLT process
      $xp->importStylesheet($xsl);
    
    
      $xml_doc = new DomDocument('1.0');
      $xml_doc->load('book.xml');
    
       echo "bool result is $r"."<br>";
       if ($html = $xp->transformToXML($xml_doc)) {
          echo $html;
      } else {
          trigger_error('XSL transformation failed.', E_USER_ERROR);
      } // if
    If i want to apply xsl, should i save the $output variabe in a file first and then apply xsl tranformation.. if i save it in a file..? i think i should save $output since that is xml rather the html one??

    Looking forward for your reply

  4. #4
    Join Date
    Mar 2007
    Location
    Athens, Greece
    Posts
    177
    Hi,

    You have to convert the string result into an xml document (no need to save if don't want) Or append it to an existing open xml and then you can apply the .xsl normally..

    Here is a complete example:

    XML file named "Names.xml":
    Code:
    <?xml version="1.0" encoding="iso-8859-1"?>
    <?xml-stylesheet type="text/xsl" href="Names.xsl"?>
    <greatpeople>
      <person>
        <firstname>Edward</firstname>
        <name>Jenne</name>
      </person>
      <person>
        <firstname>Alan</firstname>
        <name>Elion</name>
      </person>
      <person>
        <firstname>Charles</firstname>
        <name>Babbage</name>
      </person>
      <person>
        <firstname>Alan</firstname>
        <name>Touring</name>
      </person>
      <person>
        <firstname>Ada</firstname>
        <name>Byron</name>
      </person>
    </greatpeople>
    The working .xsl file named: "Names.xsl":
    (Includes also a setParameter from php use, and auto numbering in the persons output from .xsl -using the "xsl: number" tag)
    PHP Code:
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


    <xsl:output  method="html"  encoding="utf-8"  indent="yes" />
    <xsl:param  name="Order">ascending</xsl:param>   <!-- we set this param from inside php  -->


    <xsl:template match="/">   

      <html>

      <head>

        <title>XSL Test</title>  

        <!-- Use the content-type declaration to avoid strange-odd characters in your output like the ones with the spaces -->
        <meta http-equiv="content-type"  content="text/html; charset=utf-8"/>   

      </head>

      <body style="color:#223377; font:11pt verdana; padding:20px">
       <hr/>
      <h3>GREAT PERSONS:</h3><br/>

     
     <b>Search Name: </b>    <xsl:value-of  select="*/person[1]/*[1]"/>
     
    <br/> <br/> Order: <xsl:value-of  select="$Order"/>
     <br/> <br/> <br/> 


    <xsl:for-each select="greatpeople/person">
            <xsl:sort select="name"  order="{$Order}"/>
                 
        <p  xml:space="preserve"><b> <xsl:number value="position()"  format="1. "/>  </b>  <xsl:value-of  select="./*[1]"/>  <xsl:value-of  select="./*[2]"/>  </p>   

      </xsl:for-each>

     </body>
    </html>

    </xsl:template>
    </xsl:stylesheet>
    Here is the php to parse the xml and apply the transformations "Names.php":
    PHP Code:
    <?php

    // ----------------  The example uses the php 5 "DOM Functions"  to select specific node uding Xpath query ------------------ 

    $doc = new DOMDocument;                                              // Create a new dom document
    $doc->preserveWhiteSpace false;                                   // Set features
    $doc->formatOutput true;                                              // Create indents on xml

    $doc->Load('Names.xml');                                                // Load the file


    $xpath = new DOMXPath($doc);
    //$query = '/greatpeople/person/firstname[. = "Alan"]';       // The xpath (starts from root node)

    $query '/greatpeople/person[firstname= "Alan"]';            // Alternative method to the previous
    $names $xpath->query($query);                                    // A list of matched elements


    $Output="";
    foreach (
    $names as  $node) {
       
    //$Output.=$doc->saveXML($node->parentNode)."\n";         // We get the parent of  "<firstname>" element  (the entire "<person>" node and its children)
       
    $Output.=$doc->saveXML($node)."\n";            // and use the saveXML() to convert it to string  
    }

    echo 
    $Output."<br>\n\n\n";                                                  // The result as a string

    echo "<hr>\n<br><b>Below view the results  as HTML content. &nbsp; (See also the page's HTML code):</b>\n<pre>".htmlspecialchars($Output)."</pre><br>\n";


    // The previous  ($Output) is a string  -tree- of our xml file 
    // In order to transform it using our .xsl file, needs to appent it to an existing document  or convert it to a new document

    // To append: you need to create a document fragment on an existing doc, then append raw xml to that fragment and finally
    // append the fragment to our xml document

    // An easier approach is just to create a new doc from our xml string as follows:

    $doc2=new DOMDocument("1.0");   
    $doc2->preserveWhiteSpace false;  
    $doc2->formatOutput=true;

    // Get the root name of the initial xml file, so we can use a common .xsl file (without worring about node names)
    $RootName=$doc->documentElement->nodeName;   // $doc is the initial xml file


    $doc2->loadXML("<$RootName>$Output</$RootName>");         // Load xml from string  (add a root element to have a well formed doc and avoid errors
    $doc2->encoding="UTF-8";


    echo 
    "<br/>\n\n\n<pre>".htmlspecialchars($doc2->saveXML())."</pre><br/>\n\n";

    //echo $doc2->saveXML();


    //------------------------------------------  Apply our xsl transformations (using our .xsl file) -----------------------------------------------------


    $XslFile="Names.xsl";

    $xsl = new DOMDocument("1.0");
    $xsl->load($XslFile);

    $proc = new XSLTProcessor();                                                                 
    $proc->importStyleSheet($xsl); 


    $proc->setParameter'''Order''descending' );    // descending  (set the parameter of xsl file)


    //echo trim( $proc->transformToXML( $doc2 ) );             // Returns the results as a string
    //echo $proc->transformToURI( $doc2, 'Names.html' );    // Save to file   (returns the number of written bytes)


    $dom=$proc->transformToDoc$doc2 );    // Output the results  to a DOM document
    $dom->preserveWhite=false;
    $dom->formatOutput=true;
    $dom->normalize();
    echo  
    "\n\n".$dom->saveXML($dom->documentElement);     

    //------------------------------------------  Apply our xsl transformations (using our .xsl file)  (END) -----------------------------------------------

    ?>
    ----------------

    The php loads the xml, select the elements with first name Alan and then apply the .xsl file to only these selected node..

    Regards!

    Kostas

  5. #5
    Join Date
    Oct 2012
    Posts
    2

    how to pass "ALan" as a variable

    Hi

    Very usefulll example.

    I am trying though to pass Alan as a variable from a form and doesnt work
    you know why?

    the variable works outside the query but not inside:

    echo $name; ( -> result = Alan)
    $query = '/greatpeople/person/firstname[. = "$name"]'; (-> doesnt work)


    thanks in advance

  6. #6
    Join Date
    Aug 2006
    Posts
    1,933
    Have you printed out the value of your $query variable and compared it to the one in the example?

    Dave

  7. #7
    Join Date
    Oct 2012
    Posts
    2

    ok resolved

    $query = '/greatpeople/person/firstname[. = "$name"]'; (-> doesn't work)


    $query = "/greatpeople/person/firstname[. = '$name']"; (-> works fine)


    so it has to do with the quotation, don't know why..

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles