Reputation: 87
For a website i'm making i need to get data from an external XML file. I load the data like this:
$doc = new DOMDocument();
$url = 'http://myurl/results/xml/12345';
if (!$doc->load($url))
{
echo json_encode(array('error'=> 'error'));
exit;
}
$xpath = new DOMXPath($doc);
$program_date = $xpath->query('//game/date');
Then i use a foreach loop to get all the data
if($program_date){
foreach($program_date as $node){
$programArray['program_date'][] = $node->nodeValue;
}
}
The problem i'm having is that sometimes a certain game doesn't have a date. So when a game doesn't have a date, i just want it to put "-", instead of the date from the XML file. My problem is that i don't know how to check if a date is present in the data.
I used a lot of ways like isset, !isset, else, !empty, empty
$teamArray['program_kind'][] = "-";
but noting works... Can someone help me with this problem? Thanks in advance
Upvotes: 2
Views: 216
Reputation: 19482
You need to iterate the game
elements, use them as a context and fetch the data with additional XPath expressions.
But one thing first. Use DOMXPath::evaluate()
. DOMXPath::query()
only supports location paths. It can only return a node list. But XPath expressions can return scalar values, too.
$xpath = new DOMXPath($doc);
$games = $xpath->evaluate('//game');
The result of //game
will always be a DOMNodeList
object. It can be an empty list, but you can directly iterate it. A condition like if ($games)
will always be true.
foreach ($games as $game) {
Now that you have the game
element node, you can use it as an context to fetch other data.
$date = $xpath->evaluate('string(date)', $game);
string()
casts the first node of the location path into a string. If it can not match a node, it will return an empty string. Check normalize-space()
if you want to remove whitespaces at the same time.
You can validate if the game
element has a date
node using count()
.
$hasDate = $xpath->evaluate('count(date) > 0', $game);
The result of this XPath expression is always a boolean.
Upvotes: 1