1

I want to parse an xml file given as a php variable with the use of jquery: jQuery.parseXML()

This is my file content:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<?php
  $xml="<rss version='2.0'><channel><title>RSS Title</title></channel></rss>";
?>
<p id="someElement"></p>
<p id="anotherElement"></p>
<script>
  var xml = "<?php echo $xml; ?>",
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );
  $( "#someElement" ).append( $title.text() );
  $title.text( "XML Title" );
  $( "#anotherElement" ).append( $title.text() );
</script>
</body>
</html>

but what if my xml variable is like this:

$xml ='<?xml version="1.0" encoding="UTF-8" ?>
<data request-id="ID">
<data name="Name1"
    d1="0"
    d2="0231234"
    d3="32584">
    <data name="Name2"
        d4="231234"
        d5="2012-06-06 18:18:10.000607"
        d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />
    </data>
</data>';

how to display for example d1 or d4?

1 Answer 1

1

Look with the following jQuery selector '[attr="somevalue"]' and the method find() in the correct node, then use the method attr():

$(document).ready(function(){
    var xml ='<?xml version="1.0" encoding="UTF-8" ?><data request-id="ID">' + 
        '<data name="Name1" d1="0" d2="0231234" d3="32584">' + 
            '<data name="Name2" d4="231234" d5="2012-06-06 18:18:10.000607" d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />' +
            '</data>' +
        '</data>' +
        '</data>',
       d1 = $(xml).find('data[name="Name1"]').attr('d1'),
       d4 = $(xml).find('data[name="Name2"]').attr('d4');
    document.write('d1: ' + d1);
    document.write('<br>');
    document.write('d4: ' + d4);
    window.console.dirxml($(xml));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

5 Comments

it fails I even tryed with $xml.find('data').find('data').attr('d1'); but it fails to
I tested the first time with jquery integration sure, but it didnt work but now it works fine. thx
Glad I could help! Do you mind giving +1 to my answer? I adapted my answer following to your edit
why its not the best way to use a php variable in javascript?
Read about the JSON Format & PHP's functions json_encode() and json_decode() ... and AJAX ... and Server/Client communication... ;-) Good Learning & Have Fun while doing it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.