Stanislas Piotrowski
Stanislas Piotrowski

Reputation: 2704

php and xml error

I have an xml file generated by my web service, I now want to display some information from the xml

all tags in the xml are in the same level, there is no hierarchy.

However, I have these tags on either side of the document, namely:

<xml version="1.0" encoding="ISO-8859-1"><xmlresponse>

And:

</xmlresponse></xml>

afin d'utiliser une balise et de l'afficher j'ai donc le code suivant:

<?php
$document_xml = new DomDocument(); 
$resultat_html = '';
$document_xml->load('tmp/'.$_GET['n_doss'].'.xml'); 
//echo $elements = $document_xml->getElementsByTagName('rating');


$title = $document_xml->xpath('rating');
echo trim($title[0]);
?>

However, I am forwarding an error message saying:

Fatal error: Call to undefined method DOMDocument :: xpath ()

I do not know how to solve it.

Thank you in advance for your help.

Upvotes: 1

Views: 3194

Answers (2)

Paul T. Rawkeen
Paul T. Rawkeen

Reputation: 4114

Check your xml file is valid and it loads correctly by DomDocument. And why you don't use SimpleXML library ? It also supports XPath expressions the following way:

$simplexml= new SimpleXMLElement($xml); // loading RAW XML string `$xml` retrieved from WebService
$items =  $simplexml->xpath('/rating'); // querying DOM to retrieve <rating></rating> from the root of of the structure
echo $items[0]; // getting result

NOTE: DomDocument doesn't have xpath method. Use query method to apply XPath expression to the object using DomXPath like this:

$dom = new DomDocument();
$dom->load('tracks.xml');
$xpath = new DOMXPath($dom);
$query = '//distance[. > "15000"]';
$distances = $xpath->query($query);

Upvotes: 2

Gerald Versluis
Gerald Versluis

Reputation: 34128

I don't think the DOMDocument has an xpath method. Instead you can use the DOMXPath class.

Try this:

$xpath = new DOMXPath($document_xml);
$ratings = $xpath->query('rating');

Upvotes: 1

Related Questions