0

I'm using AJAX to call a PHP file which will effectively edit particular bits of content within another HTML file. My problem is that I'm not sure of the best way of targeting these particular areas.

I figured some sort of unique identifier would need to attached to the tag that needs to be edited or in a comment perhaps, and then PHP simply searches for this before doing the replacing?

fredley
  • 32,953
  • 42
  • 145
  • 236
tctc91
  • 1,343
  • 2
  • 21
  • 41
  • 1
    Use a html parser like simplehtml – jantimon Feb 07 '12 at 14:57
  • 3
    Don't whatever you do even think about using a [re̸g͇̫͛͆̾ͫ̑͆e̿̔̉x](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). – fredley Feb 07 '12 at 14:59
  • did a quick Google of simplehtml and it look's promising! I'll explore further. Thanks – tctc91 Feb 07 '12 at 14:59

2 Answers2

2

Use simplehtml for this.

You can change all <h1> to foo like this:

$html = file_get_html('http://www.google.com/');
foreach($html->find('h1') as $element) 
{
  $element->innertext = 'foo';
}
echo $html;
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
1

The simplehtmldom framework allows you to search and modify the DOM of a HTML file or url.

http://simplehtmldom.sourceforge.net/

// Create DOM from URL or file $html =
file_get_html('http://www.google.com/');

// Find all images foreach($html->find('img') as $element)
        echo $element->src . '<br>';

// Find all links foreach($html->find('a') as $element)
       echo $element->href . '<br>';

Another nice library is querypath. It is very similar to jquery:

 qp($html_code)->find('body')->text('Hello World')->writeHTML();

https://fedorahosted.org/querypath/wiki/QueryPathTutorial

jantimon
  • 36,840
  • 23
  • 122
  • 185