Skip to content
Advertisement

How to search in XML? (PHP)

I am working on a word application. I’m trying to get values from XML. My goal is getting the first and last letter of a word. Could you help me, please?

<!--?xml version='1.0'?-->
<Letters>
    <Letter category='A'>
        <FirstLetter>
            <Property>First letter is A.</Property>
        </FirstLetter>
        <LastLetter>
            <Property>Last letter is A.</Property>
        </LastLetter>
    </Letter>
    <Letter category='B'>
        <FirstLetter>
            <Property>First letter is B.</Property>
        </FirstLetter>
        <LastLetter>
            <Property>Last letter is B.</Property>
        </LastLetter>
    </Letter>
    <Letter category='E'>
        <FirstLetter>
            <Property>First letter is E.</Property>
        </FirstLetter>
        <LastLetter>
            <Property>Last letter is E.</Property>
        </LastLetter>
    </Letter>
</Letters>

PHP code:

<?php
$word = "APPLE";
$alphabet = "ABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ";
$index = strpos($alphabet, $word);
$string = $xml->xpath("//Letters/Letter[contains(text(), " . $alfabe[$rakam] . ")]/FirstLetter");
echo "<pre>" . print_r($string, true) . "</pre>";

Advertisement

Answer

The letter is in an attribute named ‘category’.

$word = "APPLE";

// bootstrap DOM
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);

// get first and last letter
$firstLetter = substr($word, 0, 1);
$lastLetter = substr($word, -1);

// fetch text from property elements
var_dump(
  $xpath->evaluate(
     "string(/Letters/Letter[@category = '$firstLetter']/FirstLetter/Property)"   
  ),
  $xpath->evaluate(
     "string(/Letters/Letter[@category = '$lastLetter']/LastLetter/Property)"   
  )
);

Or in SimpleXML

$word = "APPLE";

$letters = new SimpleXMLElement($xml);

$firstLetter = substr($word, 0, 1);
$lastLetter = substr($word, -1);

// SimpleXML does not allow for xpath expression with type casts
// So validation and cast has to be done in PHP
var_dump(
  (string)($letters->xpath(
    "/Letters/Letter[@category = '$firstLetter']/FirstLetter/Property"
  )[0] ?? ''),
  (string)($letters->xpath(
    "/Letters/Letter[@category = '$lastLetter']/LastLetter/Property"
  )[0] ?? '')
);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement