Jeff
Jeff

Reputation: 34

Using external XML uri with variables

I searched here and on the big G, I am willing to learn, but I didn't found the answer yet.

I am trying to transform external XML data with XSLT to be easily read in HTML or PHP. I tested a few things and I successfully transformed some simple XML files with XSL and PHP. The problem is that the actual XML files I need to use are not really the typical dot xml files we generally see, but more like the format "http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=14&t=0". When I use these addresses, it seems to read properly these files and the XSL stylesheet, parse the correct numbers of table cells, but return them empty.

What's wrong?

Also, can it be related to the xml formatting used by the external site? I noticed that their XML is more "XHTML styled" rather that the other files I am seen in the past.

Their style using one big tag and closed by a slash:

<vehicle id="5464" routeTag="14" dirTag="14_IB2" lat="37.7637" lon="-122.4087" secsSinceReport="86" predictable="true" heading="218" speedKmHr="0"/>

The same example, if it was writting using the usua tree:

<vehicle> <id>5464</id> <routeTag>14</routeTag> <dirTag>14_IB2</dirTag> ... </vehicle>

route14.xsl:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <h2>Route 14</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th style="text-align:left">Vehicle</th>
      <th style="text-align:left">Direction</th>
    </tr>
    <xsl:for-each select="body/vehicle">
    <tr>
      <td><xsl:value-of select="id" /></td>
      <td><xsl:value-of select="dirTag" /></td>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>   

PHP code:

<?php
// Load XML file
$xml = new DOMDocument;
$xml->load('http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=14&t=0');

// Load XSL file
$xsl = new DOMDocument;
$xsl->load('route14.xsl');

// Configure the transformer
$proc = new XSLTProcessor;

// Attach the xsl rules
$proc->importStyleSheet($xsl);

echo $proc->transformToXML($xml);
?> 

Upvotes: 1

Views: 122

Answers (2)

Ahmad
Ahmad

Reputation: 613

Your code is fine, but to get the attribute values, you need to prefix your selected attribute names with an @ in your route14.xsl

<td><xsl:value-of select="@id" /></td>
<td><xsl:value-of select="@dirTag" /></td>

Upvotes: 1

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

you are on the right path, but when accessing attribute values, you have to prefix them with @

change these lines

<tr>
  <td><xsl:value-of select="id" /></td>
  <td><xsl:value-of select="dirTag" /></td>
</tr>

to

<tr>
  <td><xsl:value-of select="@id" /></td>
  <td><xsl:value-of select="@dirTag" /></td>
</tr>

Upvotes: 2

Related Questions