0

I can parse standard xml file but I couldn't this xml file.

How can I parse this xml. I want to list 'number_name'.

Thanks.

<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<numbers>
    <number no_id="4" number_name="car" />
    <number no_id="6" number_name="bike" />
    <number no_id="11" number_name="train" />
    <number no_id="32" number_name="plane" />
</numbers>

  • Check this link this will help you https://www.w3schools.com/php/php_xml_simplexml_read.asp – Moiz Arif Aug 11 '17 at 00:19
  • look at this: https://stackoverflow.com/questions/250679/best-way-to-parse-rss-atom-feeds-with-php – yoeunes Aug 11 '17 at 00:19
  • You might want also to see this link, [SimpleXMLElement::attributes](http://php.net/manual/en/simplexmlelement.attributes.php) –  Aug 11 '17 at 01:17

2 Answers2

0

PHP's DOM classes are quite powerful and you should explore them. For example, here is one solution using DOMXPath.

https://3v4l.org/oCifF

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <numbers>
        <number no_id="4" number_name="car" />
        <number no_id="6" number_name="bike" />
        <number no_id="11" number_name="train" />
        <number no_id="32" number_name="plane" />
    </numbers>
</rss>
XML;

$doc = new DOMDocument();
$doc->loadXML($xml);

$xpath = new DOMXpath($doc);

foreach ($xpath->query('/rss/numbers/number') as $element) {
    echo $element->getAttribute('number_name').PHP_EOL;
}
car
bike
train
plane
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
0

The alternative to DOMXPath is using SimpleXML. It isn't as powerful as the DOM version, but as the name suggests it's quite simple and easy when accessing data (not so flexible in creating data though).

Using the sample you have, the two ways of doing this are...

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$xml = <<<XML
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <numbers>
        <number no_id="4" number_name="car" />
        <number no_id="6" number_name="bike" />
        <number no_id="11" number_name="train" />
        <number no_id="32" number_name="plane" />
    </numbers>
</rss>
XML;

$response = new SimpleXMLElement($xml);

echo "Element access:".PHP_EOL;
foreach ($response->numbers->number as $number )    {
    echo $number['number_name'].PHP_EOL;
}
echo "XPath:".PHP_EOL;
$xp = $response->xpath('//number');
foreach ($xp as $number )    {
    echo $number['number_name'].PHP_EOL;
}

Which gives you output of...

Element access:
car
bike
train
plane
XPath:
car
bike
train
plane
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55