MrK
MrK

Reputation: 21

Count tag occurrences between two tags using PHP

How do I get the <model> tag count between <make_1></make_1> tags? The <model> tag can be any number of tags.

<make_1>
<model_1>product Name</model_1>
<model_2>product Name</model_2>
<model_3>product Name</model_3>
<model_4>product Name</model_4>
</make_1>

Upvotes: 0

Views: 64

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

If I don't misunderstood your requirements then you can simply try like below. php.net has a super simple example for count element in parent tag. See the example here http://php.net/manual/en/simplexmlelement.count.php and I urge you to also see more about SimpleXMLElement

$xml = <<<EOF
<make_1>
  <model_1>product Name</model_1>
  <model_2>product Name</model_2>
  <model_3>product Name</model_3>
  <model_4>product Name</model_4>
</make_1>
EOF;
$elem = new SimpleXMLElement($xml);

// THIS IS JUST FOR DEBUG PURPOSE
print '<pre>';
print_r($elem);
print '<pre>';
echo "Element Count: ". $elem->count();

Output: Element Count: 4

DEMO: https://eval.in/980182

Upvotes: 2

Michael Eugene Yuen
Michael Eugene Yuen

Reputation: 2528

Just an alternative solution:

<?php
$string='<make_1>
<model_1>product Name</model_1>
<model_2>product Name</model_2>
<model_3>product Name</model_3>
<model_4>product Name</model_4>
</make_1>';

echo preg_match_all("/(<model_[^>]+\>)/i", $string, $matches);

OUTPUT:

4

Source: http://php.net/manual/en/function.preg-match-all.php

DEMO: http://sandbox.onlinephpfunctions.com/code/56fb35a317e81bd3bc6d79abec720d1ab09063d1

Upvotes: 0

chris85
chris85

Reputation: 23880

You can make the string a SimpleXML object then just count it (assuming it is always one level).

$xml = new simplexmlelement('<make_1>
<model_1>product Name</model_1>
<model_2>product Name</model_2>
<model_3>product Name</model_3>
<model_4>product Name</model_4>
</make_1>');
echo count($xml);

Demo: https://3v4l.org/V5LO5

Upvotes: 2

Related Questions