Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP reading XML with Where Clause

Let's say I have this XML file.

<book>
    <id>1</id>
    <title>Harry Potter - bla bla bla</title>
    <author>J.K Rowling</author>
</book>
<book>
    <id>2</id>
    <title>Other book</title>
    <author>A Name</author>
</book>

Is there a way where I can read via PHP and get the #2 id, or do I have to use an IF? Like jQuery selector ':eq(2)', or MySql 'WHERE id=2'

like image 247
BernaMariano Avatar asked Nov 28 '25 00:11

BernaMariano


2 Answers

There is, try SimpleXML parser of php: http://php.net/manual/en/book.simplexml.php

like image 110
Wesley Avatar answered Nov 30 '25 14:11

Wesley


If all you want is just the second one you can use DOM. It's simpler.

$dom->loadXML(<<<XML
<book>
    <id>1</id>
    <title>Harry Potter - bla bla bla</title>
    <author>J.K Rowling</author>
</book>
<book>
    <id>2</id>
    <title>Other book</title>
    <author>A Name</author>
</book>
XML;);

$book=$dom->getElementsByTagName('book')->item(1);

Edit: I just saw you say you were looking for second ID, not second element, you need xpath for that.

$xml=new SimpleXMLElement(<<<XML
<book>
    <id>1</id>
    <title>Harry Potter - bla bla bla</title>
    <author>J.K Rowling</author>
</book>
<book>
    <id>2</id>
    <title>Other book</title>
    <author>A Name</author>
</book>
XML;);
$result=$xml->xpath('/book[id=2]');

More on xpath here

like image 24
mseancole Avatar answered Nov 30 '25 16:11

mseancole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!