2

So, when I used php with MySQL I just did:

$result = $mysqli->query("SELECT * FROM table WHERE person='Bob'");

I am now using PHP with XML and I havn't a clue how to do this. I've tried googling but I don't know what this would be called in XML.

My XML is:

<People>
    <person>Bob</person>
    <about>Bob is a blob. He is 20 Years old, etc</about>
</People>
<People>
    <person>Jim</person>
    <about>Jim is 90 Years old, he plays basketball, etc</about>
</People>
<People>
    <person>Steve</person>
    <about>Steve is a superhero with the ability to fly.</about>
</People>

I'm basically trying to echo a certain Person's information. So if the user searches for Jim it would echo:

Name: Jim
About: Jim is 90 Years old, he plays basketball, etc
hakre
  • 193,403
  • 52
  • 435
  • 836
one2three
  • 1
  • 8
  • 2
    http://en.wikipedia.org/wiki/XPath – Marc B Nov 05 '14 at 21:41
  • 1
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – Jay Blanchard Nov 05 '14 at 21:47

1 Answers1

2

Use XPath.

XML:

<data>
    <People>
        <person>Bob</person>
        <about>Bob is a blob. He is 20 Years old, etc</about>
    </People>
    <People>
        <person>Jim</person>
        <about>Jim is 90 Years old, he plays basketball, etc</about>
    </People>
    <People>
        <person>Steve</person>
        <about>Steve is a superhero with the ability to fly.</about>
    </People>
</data>

PHP code:

$xml = new SimpleXMLElement($xml_string);
$result = $xml->xpath('/data/People[person="Jim"]');
var_dump($result);

Output:

array(1) {
    [0]=>
        object(SimpleXMLElement)#2 (2) {
            ["person"]=>
                string(3) "Jim"
            ["about"]=>
                string(45) "Jim is 90 Years old, he plays basketball, etc"
        }
}
AlexL
  • 1,699
  • 12
  • 20