Jump to content

Getting PHP to read an XML file


chris_2001

Recommended Posts

<?xml version="1.0" encoding="utf-8"?>
<CueCards Version="1">
  <Card Question="Question" Answer="Answer" History="YNNYN"/>
  </CueCards>

 

I want to get PHP to read the value of:

Card Question = "" 

Answer = ""

 

and the number of Ys and the number of Ns in

History=""

 

How would I go about doing this? I havn't used xml with PHP very much and can't find any good guides for what I want to do. Thanks.

Link to comment
Share on other sites

I was looking at it earlier and not knowing much about XML I couldn't get it to work because of the nature of the XML file

 

<?xml version="1.0" encoding="utf-8"?>
<CueCards Version="1">
  <Card Question="Question" Answer="Answer" History="YNNYN"/>
  </CueCards>

 

Anyone care to show me how? Sorry for my probably ignorance in advance  :-\

Link to comment
Share on other sites

Something like this?

 

<?php

$file = 'yourfile.xml';
$xml = simplexml_load_file($file);

echo "Card Question = " . $xml->Card['Question'] . "<br />";
echo "Card Answer = " . $xml->Card['Answer'] . "<br />";

?>

 

 

Yeah exactly, but what would I do when there is more than 1 Card Question and Card Answer

 

and how would i read the # of Y and N in History=""

 

Thanks for the help :)

Link to comment
Share on other sites

It only reads the first Card

 

If i have

 

<?xml version="1.0" encoding="utf-8"?>
<CueCards Version="1">
  <Card Question="Question" Answer="Answer" History="YNNYN"/>
  <Card Question="Question2" Answer="Answer2" History="YNNYN"/>
  </CueCards>

 

It doesnt work. Any help on getting it to read the 2nd one too?

Link to comment
Share on other sites

try

<?php

$str = '<?xml version="1.0" encoding="utf-8"?>
<CueCards Version="1">
  <Card Question="Question" Answer="Answer" History="YNNYN"/>
  <Card Question="Question2" Answer="Answer2" History="YNNYN"/>
  </CueCards>';
  
$xml = simplexml_load_string($str);

foreach ($xml->Card as $c)
{
echo $c['Question'], '<br>';
echo $c['Answer'], '<br>'; 
echo $c['History'], '<br>';
$k = count_chars($c['History'], 1);
foreach ($k as $ch => $val)
{
	echo chr($ch), ' : ', $val, '<br>';
}
echo '<br>';
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.