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
https://forums.phpfreaks.com/topic/105764-getting-php-to-read-an-xml-file/
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  :-\

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 :)

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?

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>';
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.